package com.ysstech.reportworld.service.impl;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.*;
import com.alibaba.druid.sql.ast.expr.*;
import com.alibaba.druid.sql.ast.statement.*;
import com.alibaba.druid.sql.dialect.oracle.ast.expr.OracleSysdateExpr;
import com.alibaba.druid.sql.dialect.oracle.ast.stmt.*;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysstech.common.cache.RedisCacheManager;
import com.ysstech.common.entity.*;
import com.ysstech.common.enums.YssEnum;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.service.DicvalueService;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.JdbcUtil;
import com.ysstech.common.util.StringUtil;
import com.ysstech.common.util.fileutil.FileWriterUtil;
import com.ysstech.reportworld.entity.*;
import com.ysstech.reportworld.enums.ReportWorldEnum;
import com.ysstech.reportworld.enums.ReportWorldFileNameEnum;
import com.ysstech.reportworld.enums.ReportWorldStatusEnum;
import com.ysstech.reportworld.mapper.SqlScriptMapper;
import com.ysstech.reportworld.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysstech.reportworld.util.TableInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 报表世界SQL脚本管理表 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2023-01-10
 */
@Service
@Slf4j
public class SqlScriptServiceImpl extends ServiceImpl<SqlScriptMapper, SqlScript> implements SqlScriptService {
    @Autowired
    private SqlScriptMapper sqlScriptMapper;
    @Autowired
    private TableService tableService;
    @Autowired
    private TableDetailService tableDetailService;
    @Autowired
    private DatabaseConfigService databaseConfigService;
    @Autowired
    private DicvalueService dicvalueService;
    @Autowired
    private RedisCacheManager redisCacheManager;
    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;
    @Autowired
    public DemandBugInfoService demandBugInfoService;
    @Autowired
    public DataDemandBugService dataDemandBugService;
    @Autowired
    private DataCustomerService dataCustomerService;
    @Autowired
    private DataModularService dataModularService;
    @Autowired
    private DataReportService dataReportService;
    @Autowired
    private TableIndexedService tableIndexedService;
    @Autowired
    private DataSqlService dataSqlService;
    @Autowired
    private TableStandardCheckService tableStandardCheckService;
    @Autowired
    private TableDetailStandardCheckService tableDetailStandardCheckService;
    @Autowired
    private TableCheckService tableCheckService;
    @Autowired
    private CompareconfigService compareconfigService;
    @Autowired
    private WeComService weComService;

    /**
     * MYSQL关键字
     */
    private String MYSQL_KEY = "KEY,VALUE,LIMIT,DESCRIBE";
    // 报表世界的admin 角色ID
    private String REPORT_WORLD_ROLEID = "df5b48a0ed134dd081d0ab8142941da4";
    private String ORACLE_FUNCTION = "to_char,TO_CHAR";

    /**
     * 查询SQL脚本列表信息
     *
     * @param sqlScript
     * @param pageBean
     * @return
     * @throws Exception
     */
    public PageBean<SqlScript> queryAllSqlScripts(SqlScript sqlScript, PageBean pageBean) throws Exception {
        SqlScript querySqlScript = this.getQueryWrapper(sqlScript);
        IPage pageSqlScript = sqlScriptMapper.queryAllSqlScript(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), querySqlScript);
        this.switchedListSqlScript(pageSqlScript.getRecords());
        return new PageBean<>(pageSqlScript);
    }

    /**
     * 查询条件
     *
     * @param sqlScript
     * @return
     * @throws Exception
     */
    private SqlScript getQueryWrapper(SqlScript sqlScript) throws Exception {
        if (null == sqlScript) {
            return null;
        }
        if (StringUtils.isNotBlank(sqlScript.getStrReport())) {
            List<String> ids = JSONArray.parseArray(sqlScript.getStrReport(), String.class);
            List<DataReport> list = new ArrayList<>();
            for (String str : ids) {
                DataReport dataReport = new DataReport();
                dataReport.setReportId(str);
                list.add(dataReport);
            }
            sqlScript.setListReport(list);
        }
        if (StringUtils.isNotBlank(sqlScript.getStrCustomer())) {
            List<String> ids = JSONArray.parseArray(sqlScript.getStrCustomer(), String.class);
            List<DataCustomer> list = new ArrayList<>();
            for (String str : ids) {
                DataCustomer dataCustomer = new DataCustomer();
                dataCustomer.setCustomerId(str);
                list.add(dataCustomer);
            }
            sqlScript.setListCustomer(list);
        }
        if (StringUtils.isNotBlank(sqlScript.getStrModular())) {
            List<String> ids = JSONArray.parseArray(sqlScript.getStrModular(), String.class);
            List<DataModular> list = new ArrayList<>();
            for (String str : ids) {
                DataModular dataModular = new DataModular();
                dataModular.setModularId(str);
                list.add(dataModular);
            }
            sqlScript.setListModular(list);
        }
        /*//获取登录用户的角色是不是有审核的权限，加载对应的数据
        List<Role> list = redisCacheManager.getLoginUserInfo().getRoles();
        boolean falg = true;
        label:
        for (Role role : list) {
            if (null == role) {
                continue;
            }
            List<Region> regionList = role.getListRegion();
            for (Region region : regionList) {
                if (null == region) {
                    continue;
                }
                // 有权限直接跳过
                if ("reportworld:sqlScript:process".equals(region.getPermissions())) {
                    falg = false;
                    break label;
                }

            }
        }
        if (falg) {
            sqlScript.setAddUser(redisCacheManager.getLoginUserInfo().getLoginId());
        }*/
        return sqlScript;
    }


    /**
     * 类型，机构等中文的转换
     *
     * @param list
     * @return
     * @throws Exception
     */
    public List<SqlScript> switchedListSqlScript(List<SqlScript> list) throws Exception {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        //状态
        Map<String, String> mapStatus = dicvalueService.getCacheDicValueMap(ReportWorldEnum.REPORT_STATUS.getCode());
        // 所在分层
        Map<String, String> mapTableLayered = dicvalueService.getCacheDicValueMap(ReportWorldEnum.REPORT_TABLE_LAYERED.getCode());
        // SQL类型
        Map<String, String> mapType = dicvalueService.getCacheDicValueMap(ReportWorldEnum.DATASQL.getCode());
        for (SqlScript script : list) {
            if (null == script) {
                continue;
            }
            //状态
            if (null != mapStatus && mapStatus.containsKey(String.valueOf(script.getStatus()))) {
                script.setStrStatus(mapStatus.get(String.valueOf(script.getStatus())));
            }
            //报表世界所在分层
            if (null != mapTableLayered && mapTableLayered.containsKey(String.valueOf(script.getLayered()))) {
                script.setStrLayered(mapTableLayered.get(String.valueOf(script.getLayered())));
            }
        }
        return list;
    }

    /**
     * 新增脚本数据信息
     *
     * @param sqlScript
     * @throws Exception
     */
    public void addSqlScript(SqlScript sqlScript) throws Exception {
        if (null == sqlScript || StringUtils.isBlank(sqlScript.getSqlScript())) {
            throw new BusinessException("获取新增报表世界脚本管理失败，请稍后重试！");
        }
        sqlScript.setId(DateUtil.generateUUID());
        sqlScript.setAddUser(redisCacheManager.getLoginUserInfo().getLoginId());
        sqlScript.setAddUserName(redisCacheManager.getLoginUserInfo().getName());
        sqlScript.setAddTime(LocalDateTime.now());
        sqlScript.setStatus(ReportWorldStatusEnum.REPORT_WAITING_REVIEW.getCode());
    /*    if (!CollectionUtils.isEmpty(redisCacheManager.getLoginUserInfo().getRoles())) {
            sqlScript.setAddWecomUrl(dicvalueService.getDicShowmsg(ReportWorldEnum.ADD_WECOM_URL.getCode(),
                    redisCacheManager.getLoginUserInfo().getRoles().get(0).getId()));
            weComService.sendMessage(sqlScript.getAddWecomUrl(), "@李双良 " + sqlScript.getAddUserName() + "提交了SQL脚本，请尽快审批！");
        }*/
        this.save(sqlScript);
    }

    /**
     * 修改脚本数据信息
     *
     * @param sqlScript
     * @throws Exception
     */
    public void editSqlScript(SqlScript sqlScript) throws Exception {
        if (sqlScript == null || StringUtils.isBlank(sqlScript.getId()) || StringUtils.isBlank(sqlScript.getSqlScript())) {
            throw new BusinessException("获取脚本管理失败，请稍后重试！");
        }
        sqlScript.setEditUser(redisCacheManager.getLoginUserInfo().getName());
        sqlScript.setEditTime(LocalDateTime.now());
        sqlScript.setStatus(ReportWorldStatusEnum.REPORT_WAITING_REVIEW.getCode());
        this.updateById(sqlScript);
    }

    /**
     * 检查SQL的规范
     *
     * @param sqlScript
     * @return
     * @throws Exception
     */
    @Transactional
    public String checkSqlScript(SqlScript sqlScript) throws Exception {
        if (null == sqlScript || StringUtils.isBlank(sqlScript.getSqlScript())) {
            throw new BusinessException("获取新增报表世界脚本管理失败，请稍后重试！");
        }
        StringBuffer msgInfo = new StringBuffer();
        ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);
        Connection connection = holder.getConnection();
        try {
            if (sqlScript.getSqlScript().toUpperCase().indexOf("CREATE TABLE") > -1
                    && null == sqlScript.getLayered()) {  // 包含建表语句，选择所在分层
                msgInfo.append("脚本中包含建表语句，请选择表所在分层").append("\r\n");
                return msgInfo.toString();
            }
            //检出SQL语句是不是标准ORACLE的
            List<SQLStatement> stmtList = null;
            try {
                String dbType = JdbcConstants.ORACLE;
                String sql = sqlScript.getSqlScript();
                //格式化输出
                String result = SQLUtils.format(sql, dbType);
                stmtList = SQLUtils.parseStatements(result, dbType);
            } catch (Exception ex) {
                msgInfo.append("解析SQL出现错误，请检查！" + ex.getMessage()).append("\r\n");
                return msgInfo.toString();
            }
            if (CollectionUtils.isEmpty(stmtList)) {
                msgInfo.append("脚本里面没有解析到SQL语句，请检查！").append("\r\n");
                return msgInfo.toString();
            }
            Map<String, String> mapInfo = new LinkedHashMap<>();
            Map<String, String> mapInfoDemandBugInfo = new LinkedHashMap<>();
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            // connection.setAutoCommit(false);
            msgInfo.append("解析出的独立语句的个数===========" + stmtList.size()).append("\r\n");
            // 统计语句个数
            int numberDel = 0, numberCreateTable = 0, numberComment = 0, numberCreateIndex = 0, numberAlterTable = 0,
                    numbDropIndex = 0, numberInsert = 0, numberUpdate = 0;
            // 按照给的语句 从前到后解析
            for (SQLStatement stmt : stmtList) {
                if (null == stmt) {
                    continue;
                }
                if (stmt instanceof SQLCreateFunctionStatement || stmt instanceof SQLCreateViewStatement
                        || stmt instanceof SQLCreateSequenceStatement || stmt instanceof SQLCreateProcedureStatement) {
                    // 插入SQL脚本信息
                    this.insertDataSqlInfo(sqlScript, mapInfo, stmt);
                    continue;
                }
                if (stmt instanceof SQLDeleteStatement) {  //  删除语句   删除修改状态
                    this.sqlDeleteStatement(stmt, sqlScript, mapInfoDemandBugInfo, connection);
                    numberDel++;
                    continue;
                }
                if (stmt instanceof SQLCreateTableStatement) {    // 建表语句
                    this.sqlCreateTableStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                    numberCreateTable++;
                    continue;
                }
                if (stmt instanceof SQLAlterTableStatement) { // alert语句
                    this.sqlAlterTableStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                    numberAlterTable++;
                    continue;
                }
                if (stmt instanceof SQLCommentStatement) {   //  增加表注释或者字段注释 COMMENT ON TABLE COMMENT ON COLUMN
                    this.sqlCommentStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                    numberComment++;
                    continue;
                }
                if (stmt instanceof SQLCreateIndexStatement) { // 创建索引
                    this.sqlCreateIndexStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                    numberCreateIndex++;
                    continue;
                }
                if (stmt instanceof SQLDropIndexStatement) {   // 删除索引
                    this.sqlDropIndexStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                    numbDropIndex++;
                    continue;
                }
                if (stmt instanceof SQLInsertStatement) {  // 插入语句 插入如果存在业务主键相同就修改
                    this.sqlInsertStatement(stmt, sqlScript, mapInfo, connection, mapInfoDemandBugInfo, msgInfo);
                    numberInsert++;
                    continue;
                }
                if (stmt instanceof SQLUpdateStatement) { //修改语句
                    this.sqlUpdateStatement(stmt, sqlScript, mapInfo, connection, mapInfoDemandBugInfo);
                    numberUpdate++;
                    continue;
                }
                if (stmt instanceof SQLBlockStatement) { // DECLARE ** CLOB;BEGIN **:= BOLB类型插入
                    this.sqlBlockStatement(stmt, sqlScript, mapInfo, connection, mapInfoDemandBugInfo, msgInfo);
                    numberInsert++;
                    continue;
                }
                throw new BusinessException("系统不支持你输入的脚本类型，请检查！" + stmt);
            }
            if (numberDel + numberCreateTable + numberComment + numberCreateIndex + numberAlterTable +
                    numbDropIndex + numberInsert + numberUpdate != stmtList.size()) {
                throw new BusinessException("解析处理的脚本个数和执行的脚本个数不一致，请检查！");
            }
            msgInfo.append("待执行删除语句" + numberDel).append("条，检查通过\r\n");
            msgInfo.append("待执行建表语句" + numberCreateTable).append("条，检查通过\r\n");
            msgInfo.append("待执行ALERT语句" + numberAlterTable + "条，检查通过").append("\r\n");
            msgInfo.append("待执行增加表注释或者增加列注释信息" + numberComment).append("条\r\n");
            msgInfo.append("待执行创建索引语句" + numberCreateIndex + "条，检查通过").append("\r\n");
            msgInfo.append("待执行删除索引句" + numbDropIndex + "条，检查通过").append("\r\n");
            msgInfo.append("待执行插入语句" + numberInsert + "条，检查通过").append("\r\n");
            msgInfo.append("待执行修改语句" + numberUpdate + "条，检查通过").append("\r\n");
            msgInfo.append("=======================================").append("\r\n");
            // 数据对应的报表，模块，客户
            this.insertDataBaseSign(sqlScript, mapInfo);
            // 检查新插入的表和字段信息是否规范
            this.tableStandardCheckInfo(sqlScript, mapInfo, msgInfo);
            this.dataBaseCheckInfo(connection, sqlScript, mapInfoDemandBugInfo, msgInfo);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException("解析SQL出现错误，请检查！" + ex.getMessage());
        } finally {
         /*   if (null != connection) {
                connection.rollback();
                connection.close();
            }*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return msgInfo.toString();
    }


    /**
     * 还原版本数据
     *
     * @param version 还原的版本号
     * @throws Exception
     */
    public void reductionData(String version) throws Exception {
        ResultSet rs = null;
        PreparedStatement pStemtSelect = null;
        PreparedStatement pStemtInsert = null;
        PreparedStatement pStemtDelete = null;
        Connection connection = null;
        try {
            if (StringUtils.isBlank(version)) {
                throw new BusinessException("没有获取到版本号，请稍后重试！");
            }
            QueryWrapper<Compareconfig> compareconfigQueryWrapper = new QueryWrapper<>();
            Compareconfig compareconfig = compareconfigService.getOne(compareconfigQueryWrapper);
            if (null == compareconfig || StringUtils.isBlank(compareconfig.getBackupTable())) {
                throw new BusinessException("没有获取到要备份的表，请稍后重试！");
            }
            Map<String, Object> mapTableName = JSON.parseObject(compareconfig.getBackupTable(), LinkedHashMap.class);
            if (CollectionUtils.isEmpty(mapTableName)) {
                throw new BusinessException("没有获取到备份表配置信息，请稍后重试！");
            }
            List<String> listTableName = (List<String>) mapTableName.get("tableNameList");
            if (CollectionUtils.isEmpty(listTableName)) {
                if (CollectionUtils.isEmpty(mapTableName)) {
                    throw new BusinessException("没有获取到备份表信息，请稍后重试！");
                }
            }
            List<String> backUpVersion = (List<String>) mapTableName.get("backUpVersion");
            if (CollectionUtils.isEmpty(backUpVersion)) { //没有备份表信息
                throw new BusinessException("没有获取到备份的信息，请稍后重试！");
            }
            connection = dataSource.getConnection();
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            // 备份表后缀
            connection.setAutoCommit(false);
            for (String backVersion : backUpVersion) {
                String tableSuffix = this.getTableSuffix(backVersion);
                if (!StringUtil.oneCase(version, backVersion) || StringUtils.isBlank(tableSuffix)) {
                    continue;
                }
                for (String tableName : listTableName) {
                    if (StringUtils.isBlank(tableName)) {
                        continue;
                    }
                    String sqlDelete = "delete  from  " + tableName;
                    pStemtDelete = connection.prepareStatement(sqlDelete);
                    pStemtDelete.execute();
                    // 还原对应版本的数据
                    String newTabaleName = tableName + tableSuffix;
                    String sqlInsert = "insert into   " + tableName + " select *  from  " + newTabaleName;
                    pStemtInsert = connection.prepareStatement(sqlInsert);
                    pStemtInsert.execute();
                }

            }
            // 修改还原版本之后的数据都为带审核状态
            // 获取所有版本号
            List<Dicvalue> list = dicvalueService.getCacheDicValueList(ReportWorldEnum.REPORT_VERSION.getCode());
            // 没有版本 或者版本号只有一个的时候不备份
            if (CollectionUtils.isEmpty(list)) {
                throw new BusinessException("没有获取到版本号，请稍后重试！");
            }
            List<String> stringList = new ArrayList<>();
            for (Dicvalue dicvalue : list) {
                if (null == dicvalue || StringUtils.isBlank(dicvalue.getValue())) {
                    continue;
                }
                // 循环到还原的版本，跳出循环
                if (version.equals(dicvalue.getValue())) {
                    break;
                }
                stringList.add(dicvalue.getValue());
            }
            if (CollectionUtils.isEmpty(stringList)) {
                return;
            }
            UpdateWrapper<SqlScript> wrapper = new UpdateWrapper<>();
            wrapper.in("VERSION", stringList);
            SqlScript sqlScript = new SqlScript();
            sqlScript.setEditUser(redisCacheManager.getLoginUserInfo().getLoginId());
            sqlScript.setEditTime(LocalDateTime.now());
            sqlScript.setStatus(ReportWorldStatusEnum.REPORT_WAITING_REVIEW.getCode());
            this.update(sqlScript, wrapper);
            connection.commit();
        } catch (Exception ex) {
            connection.rollback();
            log.error(ex.getMessage());
            throw new BusinessException("还原版本数据失败！" + ex.getMessage());
        } finally {
            if (pStemtDelete != null) {   // 关闭声明
                pStemtDelete.close();
            }
            if (pStemtInsert != null) {   // 关闭声明
                pStemtInsert.close();
            }
            if (pStemtSelect != null) {   // 关闭声明
                pStemtSelect.close();
            }
            if (rs != null) {   // 关闭声明
                rs.close();
            }
            if (connection != null) {   // 关闭声明
                connection.close();
            }
        }
    }

    /**
     * 获取能还原的版本号集合，前台显示
     *
     * @return
     */
    public List<Dicvalue> getReductionVersion() throws Exception {
        this.backUpData();
        QueryWrapper<Compareconfig> compareconfigQueryWrapper = new QueryWrapper<>();
        Compareconfig compareconfig = compareconfigService.getOne(compareconfigQueryWrapper);
        if (null == compareconfig || StringUtils.isBlank(compareconfig.getBackupTable())) {
            throw new BusinessException("没有获取到要备份的表，请稍后重试！");
        }
        Map<String, Object> map = JSON.parseObject(compareconfig.getBackupTable(), LinkedHashMap.class);
        if (CollectionUtils.isEmpty(map)) {
            return null;
        }
        List<String> backUpVersion = (List<String>) map.get("backUpVersion");
        if (CollectionUtils.isEmpty(backUpVersion)) {
            return null;
        }
        List<Dicvalue> listnew = new ArrayList<>();
        for (String version : backUpVersion) { //最大版本还没有备份，不能还原
            if (StringUtils.isBlank(version)) {
                continue;
            }
            Dicvalue dicvalue = new Dicvalue();
            dicvalue.setShowmsg(version);
            dicvalue.setValue(version);
            listnew.add(dicvalue);
        }
        return listnew;
    }

    /**
     * 备份上一个版本的数据
     *
     * @throws Exception
     */
    public void backUpData() throws Exception {
        ResultSet rs = null;
        PreparedStatement pStemtSelect = null;
        PreparedStatement pStemtCreate = null;
        PreparedStatement pStemtDrop = null;
        Connection connection = null;
        try {
            QueryWrapper<Compareconfig> compareconfigQueryWrapper = new QueryWrapper<>();
            Compareconfig compareconfig = compareconfigService.getOne(compareconfigQueryWrapper);
            if (null == compareconfig || StringUtils.isBlank(compareconfig.getBackupTable())) {
                throw new BusinessException("没有获取到要备份的表，请稍后重试！");
            }
            Map<String, Object> map = JSON.parseObject(compareconfig.getBackupTable(), LinkedHashMap.class);
            if (CollectionUtils.isEmpty(map)) {
                return;
            }
            List<String> listTableName = (List<String>) map.get("tableNameList");
            if (CollectionUtils.isEmpty(listTableName)) {
                return;
            }
            // 上一个版本的版本号的后缀作为表名后缀
            // 获取所有版本号
            List<Dicvalue> list = dicvalueService.getCacheDicValueList(ReportWorldEnum.REPORT_VERSION.getCode());
            // 没有版本 或者版本号只有一个的时候不备份
            if (CollectionUtils.isEmpty(list)) {
                throw new BusinessException("没有获取到版本号，请稍后重试！");
            }
            if (list.size() < 2) { // 只有一个版本号的是否不备份
                return;
            }
            // 上一个版本的版本号
            if (null == list.get(1) || StringUtils.isBlank(list.get(1).getValue())) {
                return;
            }
            String lastVersion = list.get(1).getValue();
            String tableSuffix = this.getTableSuffix(lastVersion);
            if (StringUtils.isBlank(tableSuffix)) {
                return;
            }
            connection = dataSource.getConnection();
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            connection.setAutoCommit(false);
            // 需要删除的版本，备份的版本个数 1 ，就是大于1的
            Integer numberVersion = (Integer) map.get("numberVersion");
            List<String> listUpVersion = (List<String>) map.get("backUpVersion");
            if (!CollectionUtils.isEmpty(listUpVersion) && numberVersion <= listUpVersion.size()) { //还没有备份数据
                if (lastVersion.equals(listUpVersion.get(0))) {
                    return;
                }
                for (String tableName : listTableName) {
                    String oldVersion = this.getTableSuffix(listUpVersion.get(0));
                    if (StringUtils.isBlank(tableName) || StringUtils.isBlank(oldVersion)) {
                        continue;
                    }
                    String oldTabaleName = tableName + oldVersion;
                    String sqlDrop = "drop  table  " + oldTabaleName;
                    pStemtDrop = connection.prepareStatement(sqlDrop);
                    pStemtDrop.execute();
                }
                listUpVersion.remove(0);
            }
            for (String version : listUpVersion) { // 备份检查，是不是已经有过备份数据了
                if (lastVersion.equals(version)) {
                    return;
                }
            }
            for (String tableName : listTableName) {
                if (StringUtils.isBlank(tableName)) {
                    continue;
                }
                String newTabaleName = tableName + tableSuffix;
                // 备份上一个版本的数据
                String sqlCreate = "create  table  " + newTabaleName + " select *  from  " + tableName;
                pStemtCreate = connection.prepareStatement(sqlCreate);
                pStemtCreate.execute();
            }
            Map<String, Object> newMap = new HashMap<>();
            if (CollectionUtils.isEmpty(listUpVersion)) {
                listUpVersion = new ArrayList<>();
                listUpVersion.add(lastVersion);
            } else {
                listUpVersion.add(lastVersion);
            }
            newMap.put("backUpVersion", listUpVersion);
            newMap.put("numberVersion", numberVersion);
            newMap.put("tableNameList", listTableName);
            String json = JSONObject.toJSONString(newMap, SerializerFeature.WriteMapNullValue);
            compareconfig.setBackupTable(json);
            compareconfigService.updateById(compareconfig);
            connection.commit();
        } catch (Exception ex) {
            connection.rollback();
            log.error("备份数据信息失败！" + ex.getMessage());
            //throw new BusinessException("备份数据信息失败！" + ex.getMessage());
        } finally {
            if (connection != null) {   // 关闭声明
                connection.close();
            }
            if (pStemtCreate != null) {   // 关闭声明
                pStemtCreate.close();
            }
            if (pStemtDrop != null) {   // 关闭声明
                pStemtDrop.close();
            }
            if (pStemtSelect != null) {   // 关闭声明
                pStemtSelect.close();
            }
            if (rs != null) {   // 关闭声明
                rs.close();
            }
        }
    }

    /**
     * 获取上一个版本的版本号后缀作为表名后缀
     *
     * @return
     * @throws Exception
     */
    private String getTableSuffix(String version) throws Exception {
        if (StringUtils.isBlank(version)) {
            throw new BusinessException("获取版本号后缀出错，请稍后重试！");
        }
        String[] arr = version.split("_");
        if (null == arr || arr.length < 2) {
            throw new BusinessException("获取版本号后缀出错，请稍后重试！");
        }
        // 备份表后缀
        return "_" + arr[1];
    }

    /**
     * 审核脚本
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Transactional
    public String processSqlScript(String ids) throws Exception {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("获取脚本管理失败，请稍后重试！");
        }
        List<String> idList = JSONArray.parseArray(ids, String.class);
        if (CollectionUtils.isEmpty(idList)) {
            throw new BusinessException("获取脚本管理失败，请稍后重试！");
        }
        StringBuffer msgInfo = new StringBuffer();
        ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);
        Connection connection = holder.getConnection();
        try {
            QueryWrapper<SqlScript> wrapper = new QueryWrapper<>();
            wrapper.in("ID", idList);
            wrapper.in("STATUS", ReportWorldStatusEnum.REPORT_WAITING_REVIEW.getCode());
            wrapper.orderByAsc("ADD_TIME");
            List<SqlScript> scriptList = this.list(wrapper);
            if (CollectionUtils.isEmpty(scriptList)) {
                throw new BusinessException("没有获取到要审核的脚本，请稍后重试！");
            }
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            // connection.setAutoCommit(false);
            // 数据对应的模块，客户，需求BUG信息 ,存放对应的主键和属于哪个基础数据
            Map<String, String> mapInfo = new LinkedHashMap<>();
            Map<String, String> mapInfoDemandBugInfo = new LinkedHashMap<>();
            for (SqlScript sqlScript : scriptList) {
                if (null == scriptList || StringUtils.isBlank(sqlScript.getId()) || StringUtils.isBlank(sqlScript.getSqlScript())) {
                    continue;
                }
                String sql = sqlScript.getSqlScript();
                String dbType = JdbcConstants.ORACLE;
                //检出SQL语句是不是标准ORACLE的
                List<SQLStatement> stmtList = null;
                try {
                    //格式化输出
                    String result = SQLUtils.format(sql, dbType);
                    stmtList = SQLUtils.parseStatements(result, dbType);
                } catch (Exception ex) {
                    msgInfo.append("解析SQL出现错误，请检查！" + ex.getMessage()).append("\r\n");
                    return msgInfo.toString();
                }
                if (CollectionUtils.isEmpty(stmtList)) {
                    msgInfo.append("脚本里面没有解析到SQL语句，请检查！").append("\r\n");
                    return msgInfo.toString();
                }
                msgInfo.append("解析出的独立语句的个数===========" + stmtList.size()).append("\r\n");
                // 查询当前版本的所有需求BUG
                QueryWrapper<DemandBugInfo> queryWrapper = new QueryWrapper<>();
                //queryWrapper.eq("VERSION", sqlScript.getVersion());
                List<DemandBugInfo> listDemandBugInfo = demandBugInfoService.list(queryWrapper);
                Map<String, String> mapDemandBugInfo = new HashMap<>();
                if (!CollectionUtils.isEmpty(listDemandBugInfo)) {
                    for (DemandBugInfo demandBugInfo : listDemandBugInfo) {
                        if (null == demandBugInfo) {
                            continue;
                        }
                        mapDemandBugInfo.put(demandBugInfo.getDemandBugNum(), demandBugInfo.getId());
                    }
                }
                // 统计语句个数
                int numberDel = 0, numberCreateTable = 0, numberComment = 0, numberCreateIndex = 0, numberAlterTable = 0,
                        numbDropIndex = 0, numberInsert = 0, numberUpdate = 0;
                sqlScript.setStatus(ReportWorldStatusEnum.REPORT_UNDER_REVIEW.getCode());
                this.updateById(sqlScript);
                // 按照编号删除对应的数据,新增的数据，修改的数据的数据不会修改这个，修改后审核
                this.removeDataByFileNmae(sqlScript, connection);
                // 按照给的语句 从前到后解析
                for (SQLStatement stmt : stmtList) {
                    if (null == stmt) {
                        continue;
                    }
                    if (stmt instanceof SQLCreateFunctionStatement || stmt instanceof SQLCreateViewStatement
                            || stmt instanceof SQLCreateSequenceStatement || stmt instanceof SQLCreateProcedureStatement) {
                        // 插入SQL脚本信息
                        this.insertDataSqlInfo(sqlScript, mapInfo, stmt);
                        continue;
                    }
                    if (stmt instanceof SQLDeleteStatement) {  //  删除语句   删除修改状态
                        this.sqlDeleteStatement(stmt, sqlScript, mapInfoDemandBugInfo, connection);
                        numberDel++;
                        continue;
                    }
                    if (stmt instanceof SQLCreateTableStatement) {    // 建表语句
                        this.sqlCreateTableStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                        numberCreateTable++;
                        continue;
                    }
                    if (stmt instanceof SQLAlterTableStatement) { // alert语句
                        this.sqlAlterTableStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                        numberAlterTable++;
                        continue;
                    }
                    if (stmt instanceof SQLCommentStatement) {   //  增加表注释或者字段注释 COMMENT ON TABLE COMMENT ON COLUMN
                        this.sqlCommentStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                        numberComment++;
                        continue;
                    }
                    if (stmt instanceof SQLCreateIndexStatement) { // 创建索引
                        this.sqlCreateIndexStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                        numberCreateIndex++;
                        continue;
                    }
                    if (stmt instanceof SQLDropIndexStatement) {   // 删除索引
                        this.sqlDropIndexStatement(stmt, sqlScript, mapInfo, mapInfoDemandBugInfo);
                        numbDropIndex++;
                        continue;
                    }
                    if (stmt instanceof SQLInsertStatement) {  // 插入语句 插入如果存在业务主键相同就修改
                        this.sqlInsertStatement(stmt, sqlScript, mapInfo, connection, mapInfoDemandBugInfo, msgInfo);
                        numberInsert++;
                        continue;
                    }
                    if (stmt instanceof SQLUpdateStatement) { //修改语句
                        this.sqlUpdateStatement(stmt, sqlScript, mapInfo, connection, mapInfoDemandBugInfo);
                        numberUpdate++;
                        continue;
                    }
                    if (stmt instanceof SQLBlockStatement) { // DECLARE ** CLOB;BEGIN **:= BOLB类型插入
                        this.sqlBlockStatement(stmt, sqlScript, mapInfo, connection, mapInfoDemandBugInfo, msgInfo);
                        numberInsert++;
                        continue;
                    }
                    throw new BusinessException("系统不支持你输入的脚本类型，请检查！" + stmt);
                }
                if (numberDel + numberCreateTable + numberComment + numberCreateIndex + numberAlterTable +
                        numbDropIndex + numberInsert + numberUpdate != stmtList.size()) {
                    throw new BusinessException("解析处理的脚本个数和执行的脚本个数不一致，请检查！");
                }
                msgInfo.append("执行删除语句成功" + numberDel).append("条\r\n");
                msgInfo.append("执行建表语句成功" + numberCreateTable).append("条\r\n");
                msgInfo.append("执行ALERT语句成功" + numberAlterTable + "条").append("\r\n");
                msgInfo.append("执行增加表注释或者增加列注释信息成功" + numberComment).append("条\r\n");
                msgInfo.append("执行创建索引语句成功" + numberCreateIndex + "条").append("\r\n");
                msgInfo.append("执行删除索引句成功" + numbDropIndex + "条").append("\r\n");
                msgInfo.append("执行插入语句成功" + numberInsert + "条").append("\r\n");
                msgInfo.append("执行修改语句成功" + numberUpdate + "条").append("\r\n");
                msgInfo.append("=======================================").append("\r\n");
                // 数据对应的报表，模块，客户
                this.insertDataBaseSign(sqlScript, mapInfo);
                // 修改记录
                this.insertDataBasedataDemandBug(sqlScript, mapInfoDemandBugInfo, mapDemandBugInfo);
                // 检查新插入的表和字段信息是否规范
                this.tableStandardCheckInfo(sqlScript, mapInfoDemandBugInfo, msgInfo);
                this.dataBaseCheckInfo(connection, sqlScript, mapInfoDemandBugInfo, msgInfo);
                sqlScript.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                sqlScript.setApprovalUser(redisCacheManager.getLoginUserInfo().getLoginId());
                sqlScript.setApprovalTime(LocalDateTime.now());
                this.updateById(sqlScript);
            }
            // connection.commit();
        } catch (Exception ex) {
            log.error(ex.getMessage());
            //  connection.rollback();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            msgInfo.append("审核数据失败原因：" + ex.getMessage()).append("\r\n");
        } finally {
          /*  if (null != connection) {
                connection.close();
            }*/
        }
        return msgInfo.toString();
    }

    /**
     * 插入SQL脚本信息  检查时候存在函数，视图等语句
     *
     * @return
     */
    private void insertDataSqlInfo(SqlScript sqlScript, Map<String, String> mapInfo, SQLStatement stmt) throws Exception {
        try {

            String dataSqlName = "", datasql = "";
            int ftype = 0;
            if ((stmt instanceof SQLCreateFunctionStatement)) { // 函数
                throw new BusinessException("提交的脚本中包含的函数脚本，系统现在不允许提交函数脚本，请检查！");
              /*      ftype = 1;
                    SQLCreateFunctionStatement createFunctionStatement = (SQLCreateFunctionStatement) stmt;
                    SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) createFunctionStatement.getName();
                    dataSqlName = identifierExpr.getSimpleName();
                    if (StringUtils.isBlank(dataSqlName)) {
                        throw new BusinessException("没有获取到创建函数的名称信息，请检查！");
                    }
                    datasql = createFunctionStatement.toString();
                    if (StringUtils.isBlank(datasql)) {
                        throw new BusinessException("没有获取到创建函数的语句信息，请检查！");
                    }
                    number++;*/
            }
            if ((stmt instanceof SQLCreateViewStatement)) { // 视图
                throw new BusinessException("提交的脚本中包含的视图脚本，系统现在不允许提交视图脚本，请检查！");
                   /* ftype = 2;
                    SQLCreateViewStatement createViewStatement = (SQLCreateViewStatement) stmt;
                    SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) createViewStatement.getTableSource().getExpr();
                    dataSqlName = identifierExpr.getSimpleName(); // 创建的视图名称
                    if (StringUtils.isBlank(dataSqlName)) {
                        throw new BusinessException("没有获取到创建视图的名称信息，请检查！");
                    }
                    datasql = createViewStatement.toString();
                    if (StringUtils.isBlank(datasql)) {
                        throw new BusinessException("没有获取到创建视图的语句信息，请检查！");
                    }
                    number++;*/
            }
            if ((stmt instanceof SQLCreateSequenceStatement)) { // 序列
                throw new BusinessException("提交的脚本中包含的序列脚本，系统现在不允许提交序列脚本，请检查！");
                   /* ftype = 4;
                    SQLCreateSequenceStatement createSequenceStatement = (SQLCreateSequenceStatement) stmt;
                    SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) createSequenceStatement.getName();
                    dataSqlName = identifierExpr.getSimpleName();
                    if (StringUtils.isBlank(dataSqlName)) {
                        throw new BusinessException("没有获取到创建序列的名称信息，请检查！");
                    }
                    datasql = createSequenceStatement.toString();
                    if (StringUtils.isBlank(datasql)) {
                        throw new BusinessException("没有获取到创建序列的语句信息，请检查！");
                    }
                    number++;*/
            }
            if ((stmt instanceof SQLCreateProcedureStatement)) { // 存储过程
                throw new BusinessException("提交的脚本中包含的存储过程脚本，系统现在不允许提交存储过程脚本，请检查！");
                   /* ftype = 5;
                    SQLCreateProcedureStatement createProcedureStatement = (SQLCreateProcedureStatement) stmt;
                    SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) createProcedureStatement.getName();
                    dataSqlName = identifierExpr.getSimpleName();
                    if (StringUtils.isBlank(dataSqlName)) {
                        throw new BusinessException("没有获取到创建存储过程的名称信息，请检查！");
                    }
                    datasql = createProcedureStatement.toString();
                    if (StringUtils.isBlank(datasql)) {
                        throw new BusinessException("没有获取到创建存储过程的语句信息，请检查！");
                    }
                    number++;*/
            }
            if (StringUtils.isBlank(dataSqlName) || StringUtils.isBlank(datasql)) {
                return;
            }
            // 查询SQL脚本时候已经存在
            QueryWrapper<DataSql> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("NAME", dataSqlName.toUpperCase());
            DataSql dataSql = dataSqlService.getOne(queryWrapper);
            if (null != dataSql) {
                dataSql.setDatasql(datasql);
                dataSql.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                dataSql.setEditUser(sqlScript.getAddUser());
                dataSql.setEditTime(LocalDateTime.now());
                dataSqlService.updateById(dataSql);
                mapInfo.put(dataSql.getId(), ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
                return;
            }
            DataSql dataSqlAdd = new DataSql();
            dataSqlAdd.setId(DateUtil.generateUUID());
            dataSqlAdd.setAddUser(sqlScript.getAddUser());
            dataSqlAdd.setAddTime(LocalDateTime.now());
            dataSqlAdd.setName(dataSqlName.toUpperCase());
            dataSqlAdd.setChineseName(dataSqlName.toUpperCase());
            dataSqlAdd.setDatasql(datasql);
            dataSqlAdd.setDataBaseType(sqlScript.getDataBaseType());
            dataSqlAdd.setType(ftype);
            dataSqlAdd.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
            dataSqlAdd.setVersion(sqlScript.getVersion());
            mapInfo.put(dataSqlAdd.getId(), ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
            dataSqlService.save(dataSqlAdd);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException("解析SQL脚本语句出错！" + ex.getMessage());
        }
    }

    /**
     * 重复执行的时候
     */
    private void removeDataByFileNmae(SqlScript sqlScript, Connection connection) throws Exception {
        PreparedStatement pStemt = null;
        try {
            // 删除当前数据插入的表
            QueryWrapper<Table> tableQueryWrapper = new QueryWrapper<>();
            tableQueryWrapper.eq("FILE_NAME", sqlScript.getId());
            tableService.remove(tableQueryWrapper);
            // 删除当前数据插入的表明细信息
            QueryWrapper<TableDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("FILE_NAME", sqlScript.getId());
            tableDetailService.remove(detailQueryWrapper);
            // 删除当前数据插入的模块，客户，报表信息关联信息
            QueryWrapper<DataModular> modularQueryWrapper = new QueryWrapper<>();
            modularQueryWrapper.in("FILE_NAME", sqlScript.getId());
            dataModularService.remove(modularQueryWrapper);
            QueryWrapper<DataReport> reportQueryWrapper = new QueryWrapper<>();
            reportQueryWrapper.in("FILE_NAME", sqlScript.getId());
            dataReportService.remove(reportQueryWrapper);
            QueryWrapper<DataCustomer> customerQueryWrapper = new QueryWrapper<>();
            customerQueryWrapper.in("FILE_NAME", sqlScript.getId());
            dataCustomerService.remove(customerQueryWrapper);
            // 删除修改记录信息
            QueryWrapper<DataDemandBug> demandBugQueryWrapper = new QueryWrapper<>();
            demandBugQueryWrapper.eq("FILE_NAME", sqlScript.getId());
            dataDemandBugService.remove(demandBugQueryWrapper);
            //删除表的索引信息
            QueryWrapper<TableIndexed> indexedQueryWrapper = new QueryWrapper<>();
            indexedQueryWrapper.eq("FILE_NAME", sqlScript.getId());
            tableIndexedService.remove(indexedQueryWrapper);
            //删除对应基础数据
            List<DatabaseConfig> list = databaseConfigService.selectListDatabaseConfig();
            connection.setAutoCommit(false);
            if (!CollectionUtils.isEmpty(list)) {
                for (DatabaseConfig config : list) {
                    if (null == config || StringUtils.isBlank(config.getCode())) {
                        continue;
                    }
                    StringBuffer buffer = new StringBuffer();
                    buffer.append("DELETE FROM " + config.getCode() + " WHERE RW_DB_FILE_NAME=?");
                    pStemt = connection.prepareStatement(buffer.toString());
                    pStemt.setString(1, sqlScript.getId());
                    pStemt.executeUpdate();
                }
            }
            // 删除对应SQL语句
            QueryWrapper<DataSql> dataSqlQueryWrapper = new QueryWrapper<>();
            dataSqlQueryWrapper.eq("NAME", sqlScript.getId());
            dataSqlService.remove(dataSqlQueryWrapper);
        } catch (Exception ex) {
            log.error("删除SQL脚本对应数据信息失败！");
            throw new BusinessException("删除SQL脚本对应数据信息失败！" + ex.getMessage());
        } finally {
            if (pStemt != null) {   // 关闭声明
                pStemt.close();
            }
        }
    }


    /**
     * 建表语句的解析
     *
     * @param stmt
     * @param sqlScript
     * @return
     * @throws Exception
     */
    private void sqlCreateTableStatement(SQLStatement stmt, SqlScript sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        List<Table> tableList = new ArrayList<>();
        try {
            // 包含有建表语句，就需要选择表所在分层
            if (null == sqlScript.getLayered()) {
                throw new BusinessException("脚本中包含建表语句，请选择表所在分层！");
            }
            SQLCreateTableStatement statement = (SQLCreateTableStatement) stmt;
            // 获取表名
            SQLExprTableSource tableSource = statement.getTableSource();
            String tableName = tableSource.getName().getSimpleName();
            if (StringUtils.isBlank(tableName)) {
                throw new BusinessException("建表语句没有获到正确的表名信息！");
            }
            QueryWrapper<Table> wrapper = new QueryWrapper<>();
            wrapper.eq("NAME", tableName.toUpperCase());
            Table tableOld = tableService.getOne(wrapper);
            String tableId = "";
            boolean falg = false; // 表是否存在
            if (null != tableOld) { // 表已经存在修改表信息
                // throw new BusinessException("系统已经存在表信息，请检查！" + tableName);
                tableOld.setName(tableName);
                tableOld.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                tableOld.setVersion(sqlScript.getVersion());
                if (null != sqlScript.getLayered()) {
                    tableOld.setLayered(sqlScript.getLayered());
                }
                tableList.add(tableOld);
                tableService.updateById(tableOld);
                mapInfo.put(tableOld.getId(), ReportWorldEnum.REPORT_TABLE_CODE.getCode());
                mapInfoDemandBugInfo.put(tableOld.getId(), ReportWorldEnum.REPORT_TABLE_CODE.getCode());
                tableId = tableOld.getId();
                falg = true;
            } else {
                //表不存在创建表信息
                tableId = DateUtil.generateUUID();
                Table table = new Table();
                table.setId(tableId);
                table.setName(tableName);
                table.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                table.setFileName(sqlScript.getId()); // 表里文件来源脚本的编号
                table.setVersion(sqlScript.getVersion());
                table.setLayered(sqlScript.getLayered());
                tableList.add(table);
                tableService.save(table);
                mapInfo.put(tableId, ReportWorldEnum.REPORT_TABLE_CODE.getCode());
                mapInfoDemandBugInfo.put(tableId, ReportWorldEnum.REPORT_TABLE_CODE.getCode());
            }
            List<SQLTableElement> list = statement.getTableElementList();
            int sequence = 1;
            // 主键字段集合
            List<String> pkList = new ArrayList<>();
            for (SQLTableElement element : list) {
                if (null == element) {
                    throw new BusinessException("获取建表语句信息失败，请稍后重试！" + tableName);
                }
                // 创建主键语句   CONSTRAINT  PRIMARY KEY ()
                if (element instanceof OraclePrimaryKey) {
                    OraclePrimaryKey primaryKey = (OraclePrimaryKey) element;
                    List<SQLSelectOrderByItem> columns = primaryKey.getColumns(); // 主键字段
                    if (!CollectionUtils.isEmpty(columns)) {
                        for (SQLSelectOrderByItem item : columns) {
                            if (null == item) {
                                continue;
                            }
                            SQLIdentifierExpr expr = (SQLIdentifierExpr) item.getExpr();
                            pkList.add(expr.getName());
                        }
                    }
                }
            }
            for (SQLTableElement element : list) {
                if (null == element) {
                    throw new BusinessException("获取建表语句信息失败，请稍后重试！" + tableName);
                }
                if (element instanceof OraclePrimaryKey) { //主键已经取出来了
                    continue;
                }
                if (element instanceof SQLColumnDefinition) {
                    SQLColumnDefinition definition = (SQLColumnDefinition) element;
                    sequence++;
                    TableDetail detail = this.getTableDetail(definition, tableId, sequence, sqlScript);
                    if (!CollectionUtils.isEmpty(pkList) && pkList.contains(detail.getColumnName())) {
                        detail.setPrimaryKey(1);
                    }
                    if (falg) { //表已经存在查询字段是否存在
                        QueryWrapper<TableDetail> detailQueryWrapper = new QueryWrapper<>();
                        detailQueryWrapper.eq("TABLE_ID", tableId);
                        detailQueryWrapper.eq("COLUMN_NAME", detail.getColumnName().toUpperCase());
                        TableDetail detailOld = tableDetailService.getOne(detailQueryWrapper);
                        if (null != detailOld) {
                            BeanUtils.copyProperties(detail, detailOld, new String[]{"id", "sequence"});
                            detailOld.setEditUser(sqlScript.getAddUser());
                            detailOld.setEditTime(LocalDateTime.now());
                            detailOld.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                            detailOld.setVersion(sqlScript.getVersion());
                            tableDetailService.updateById(detailOld);
                            mapInfo.put(detailOld.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                            mapInfoDemandBugInfo.put(detailOld.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                        } else {
                            tableDetailService.save(detail);
                            mapInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                            mapInfoDemandBugInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                        }
                    } else {
                        tableDetailService.save(detail);
                        mapInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                        mapInfoDemandBugInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                    }
                } else {
                    throw new BusinessException("建表语句获取字段信息失败！" + stmt.getParent());
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException("解析建表语句出错！" + ex.getMessage());
        }
    }

    /**
     * 接卸增加字段信息的脚本
     *
     * @param element
     * @param tableId
     * @param sequence
     * @param sqlScript
     * @return
     * @throws Exception
     */
    private TableDetail getTableDetail(SQLColumnDefinition element, String tableId, int sequence, SqlScript sqlScript) throws Exception {
        return this.getTableDetail(element, tableId, sequence, sqlScript, true);
    }

    /**
     * 接卸增加字段信息的脚本
     *
     * @param element
     * @param tableId
     * @param sequence
     * @param sqlScript
     * @param isAdd     是否新增
     * @return
     * @throws Exception
     */
    private TableDetail getTableDetail(SQLColumnDefinition element, String tableId, int sequence, SqlScript sqlScript, boolean isAdd) throws Exception {
        SQLColumnDefinition definition = element;
        ColumnInfo columnInfo = new ColumnInfo();
        // 字段名称
        SQLIdentifierExpr expr = (SQLIdentifierExpr) definition.getName();
        if (StringUtils.isBlank(expr.getName())) {
            throw new BusinessException("获取字段名称出错，请稍后重试！");
        }
        columnInfo.setName(expr.getName().toUpperCase());
        // 字段类型和长度相关
        SQLDataTypeImpl sqlDataType = (SQLDataTypeImpl) definition.getDataType();
        if (isAdd && null == sqlDataType) {
            throw new BusinessException("添加的字段没有获取到字段类型和长度信息！");
        }
        if (null != sqlDataType) {
            String name = sqlDataType.getName();
            if (StringUtils.isNotBlank(name)) {
                columnInfo.setDataTypeName(name.toUpperCase());
            }
            List<SQLExpr> exprList = sqlDataType.getArguments();
            for (int i = 0; i < exprList.size(); i++) {
                if (null == exprList.get(i)) {
                    continue;
                }
                if (i == 0) { // 整数位数
                    SQLIntegerExpr integerExpr = (SQLIntegerExpr) exprList.get(i);
                    columnInfo.setPrecision(integerExpr.getNumber().intValue());
                    continue;
                }
                if (i == 1) { // 小数位数
                    SQLIntegerExpr integerExpr = (SQLIntegerExpr) exprList.get(i);
                    columnInfo.setScale(integerExpr.getNumber().intValue());
                    break;
                }
            }
        }
        // 默认值
        SQLExpr sqlExpr = definition.getDefaultExpr();
        if (null != sqlExpr) {
            if (sqlExpr instanceof SQLCharExpr) { //字符类型
                SQLCharExpr invokeExpr = (SQLCharExpr) definition.getDefaultExpr();
                if (null != invokeExpr) {
                    // 字符类型的默认值要有单引号
                    columnInfo.setDefaultValue("'" + invokeExpr.getText() + "'");
                }
            } else if (sqlExpr instanceof SQLIntegerExpr) { //数字类型
                SQLIntegerExpr invokeExpr = (SQLIntegerExpr) definition.getDefaultExpr();
                if (null != invokeExpr) {
                    columnInfo.setDefaultValue(invokeExpr.getNumber().toString());
                }
            } else if (sqlExpr instanceof SQLMethodInvokeExpr) { // 方法类型 如 sys_guid()
                SQLMethodInvokeExpr invokeExpr = (SQLMethodInvokeExpr) definition.getDefaultExpr();
                if (null != invokeExpr) {
                    columnInfo.setDefaultValue(invokeExpr.toString());
                }
            } else if (sqlExpr instanceof OracleSysdateExpr) { // ORACLE 的 SYSDATE默认值
                OracleSysdateExpr invokeExpr = (OracleSysdateExpr) definition.getDefaultExpr();
                if (null != invokeExpr) {
                    columnInfo.setDefaultValue(invokeExpr.toString());
                }
            } else if (sqlExpr instanceof SQLNumberExpr) { //字符类型
                SQLNumberExpr sqlNumberExpr = (SQLNumberExpr) sqlExpr;
                if (null != sqlNumberExpr) {
                    columnInfo.setDefaultValue(sqlNumberExpr.getNumber().toString());
                }
            } else if (sqlExpr instanceof SQLTimestampExpr) {
                SQLTimestampExpr invokeExpr = (SQLTimestampExpr) sqlExpr;
                if (null != invokeExpr) {
                    columnInfo.setDefaultValue(invokeExpr.getLiteral());
                }
            } else {
                throw new BusinessException("系统没有解析到你值，请联系管理员！" + sqlExpr.getParent());
            }
            String defaultValue = tableDetailService.getColumnDefault(columnInfo.getDefaultValue());
            columnInfo.setDefaultValue(defaultValue);
        }
        // 是否主键，为空的判断
        List<SQLColumnConstraint> constraintList = definition.getConstraints();
        columnInfo.setIsNull("1");
        columnInfo.setPrimaryKey(2);
        if (!CollectionUtils.isEmpty(constraintList)) {
            for (SQLColumnConstraint constraint : constraintList) {
                if (null == constraint) {
                    continue;
                }
                if (constraint instanceof SQLNotNullConstraint) {
                    columnInfo.setIsNull("2");
                }
                if (constraint instanceof SQLColumnPrimaryKey) {
                    columnInfo.setPrimaryKey(1);
                }
            }
        }
        // 转换成表明细信息的集合
        TableDetail detail = TableInfoUtil.getReportTableDetail(columnInfo, tableId);
        detail.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
        detail.setSequence(sequence);
        if (isAdd) {
            detail.setFileName(sqlScript.getId()); // 表里文件来源脚本的编号
        }
        detail.setVersion(sqlScript.getVersion());
        return detail;
    }

    /**
     * 增加表注释或者增加列注释信息
     *
     * @param stmt
     * @param sqlScript
     * @return
     */
    private void sqlCommentStatement(SQLStatement stmt, SqlScript sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        List<Table> tableList = new ArrayList<>();
        List<TableDetail> tableDetailList = new ArrayList<>();
        try {
            SQLCommentStatement statement = (SQLCommentStatement) stmt;
            // 增加表说明还是列说明
            SQLCommentStatement.Type type = statement.getType();
            if (null == type) {
                throw new BusinessException("增加表注释或者增加列注释信息没有获取到要添加说明的列或者表类型，请检查！" + statement.toString());
            }
            SQLExprTableSource tableSource = statement.getOn();
            if (null == tableSource) {
                throw new BusinessException("增加表注释或者增加列注释信息没有获取到要对应的表名信息，请检查！" + statement.toString());
            }
            // 增加表说明
            if ("TABLE".equals(type.name())) {
                if (null == statement.getComment()) {
                    throw new BusinessException("表注释信息不能为空，请检查！" + statement.getParent());
                }
                if (statement.getComment() instanceof SQLNullExpr) {
                    throw new BusinessException("表段注释信息不能为空，请检查！" + statement.getParent());
                }
                SQLCharExpr expr = (SQLCharExpr) statement.getComment(); // 表的中文说明
                String tableName = tableSource.getName().getSimpleName(); //要增加的表名
                Table table = this.getTableInfo(tableName);
                String chineseName = expr.getText();
                table.setChineseName(chineseName);
                table.setFileName(sqlScript.getId());
                table.setVersion(sqlScript.getVersion());
                tableList.add(table);   // 修改表说明
                mapInfo.put(table.getId(), ReportWorldEnum.REPORT_TABLE_CODE.getCode());
                mapInfoDemandBugInfo.put(table.getId(), ReportWorldEnum.REPORT_TABLE_CODE.getCode());
            } else if ("COLUMN".equals(type.name())) {
                if (null == statement.getComment()) {
                    throw new BusinessException("字段注释信息不能为空，请检查！" + statement.toString());
                }
                if (statement.getComment() instanceof SQLNullExpr) {
                    throw new BusinessException("字段注释信息不能为空，请检查！" + statement.toString());
                }
                SQLCharExpr expr = (SQLCharExpr) statement.getComment(); // 字段的中文说明
                SQLPropertyExpr propertyExpr = (SQLPropertyExpr) tableSource.getExpr();
                SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) propertyExpr.getOwner();
                String tableName = identifierExpr.getName();
                Table table = this.getTableInfo(tableName);
                String columnName = tableSource.getName().getSimpleName(); //要增加的字段名称
                if (StringUtils.isBlank(columnName)) {
                    throw new BusinessException("增加列注释信息要添加字段说明的表字段信息不存在，请检查！" + statement.toString());
                }
                QueryWrapper<TableDetail> detailQueryWrapper = new QueryWrapper<>();
                detailQueryWrapper.eq("TABLE_ID", table.getId());
                detailQueryWrapper.eq("COLUMN_NAME", columnName.toUpperCase());
                TableDetail detail = tableDetailService.getOne(detailQueryWrapper);
                if (null == detail) {
                    throw new BusinessException("增加列注释信息要添加字段说明的表字段信息不存在，请检查！" + statement.toString());
                }
                String chineseName = expr.getText();
                detail.setColumnChineseName(chineseName); // 字段说明
                if (StringUtils.isNotBlank(chineseName) && chineseName.indexOf("【") > -1 && chineseName.indexOf("】") > -1) {
                    String name = StringUtils.substring(chineseName, 0, chineseName.indexOf("【"));
                    detail.setColumnChineseName(name); // 字段说明
                    String codeName = StringUtils.substring(chineseName, chineseName.indexOf("【") + 1, chineseName.indexOf("】"));
                    detail.setCodeName(codeName);
                }
                detail.setFileName(sqlScript.getId());
                detail.setVersion(sqlScript.getVersion());
                mapInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                mapInfoDemandBugInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                tableDetailList.add(detail);
            }
            if (!CollectionUtils.isEmpty(tableList)) {
                tableService.updateBatchById(tableList);
            }
            if (!CollectionUtils.isEmpty(tableDetailList)) {
                tableDetailService.updateBatchById(tableDetailList);
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException("增加表注释或者增加列注释信息出错！" + ex.getMessage());
        }
    }

    /**
     * 插入语句解析
     *
     * @param stmt
     * @param sqlScript
     * @return
     */
    private void sqlInsertStatement(SQLStatement stmt, SqlScript
            sqlScript, Map<String, String> mapInfo, Connection connection,
                                    Map<String, String> mapInfoDemandBugInfo, StringBuffer msgInfo) throws Exception {
        this.sqlInsertStatement(stmt, sqlScript, mapInfo, connection, mapInfoDemandBugInfo, msgInfo, null);
    }

    /**
     * 插入语句解析
     *
     * @param stmt
     * @param sqlScript
     * @return
     */
    private void sqlInsertStatement(SQLStatement stmt, SqlScript
            sqlScript, Map<String, String> mapInfo, Connection connection,
                                    Map<String, String> mapInfoDemandBugInfo, StringBuffer msgInfo, Map<String, Object> mapDeclare) throws Exception {
        try {
            // 存在字段名称和字段信息
            Map<String, List<Object>> mapCoulmnName = new HashMap<>();
            Map<String, List<List<Object>>> mapCoulmnValue = new HashMap<>();
            SQLInsertStatement statement = (SQLInsertStatement) stmt;
            //获取表名
            SQLExprTableSource tableSource = statement.getTableSource();
            SQLIdentifierExpr expr = (SQLIdentifierExpr) tableSource.getExpr();
            String tableName = expr.getName(); // 表名
            if (StringUtils.isBlank(tableName)) {
                throw new BusinessException("插入语句中没有获取到表名，请检查！" + statement.getParent());
            }
            tableName = tableName.toUpperCase();
            List<SQLExpr> sqlExprList = statement.getColumns();
            if (CollectionUtils.isEmpty(sqlExprList)) {
                throw new BusinessException("插入语句中没有获取到插入字段的信息，请检查！" + statement.getParent());
            }
            List<Object> listCoulmnName = new ArrayList<>();
            for (SQLExpr sqlExpr : sqlExprList) {
                SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) sqlExpr;
                String name = identifierExpr.getName();
                listCoulmnName.add(name.toUpperCase());
            }
            // 已经存在的要和之前的字段个数比较时候一致
            if (mapCoulmnName.containsKey(tableName) && mapCoulmnName.get(tableName).size() != listCoulmnName.size()) {
                throw new BusinessException("相同插入语句的字段个数不一致，请检查！" + statement.getParent());
            }
            mapCoulmnName.put(tableName, listCoulmnName);
            List<SQLInsertStatement.ValuesClause> valuesClauseList = statement.getValuesList();
            if (CollectionUtils.isEmpty(valuesClauseList)) {
                throw new BusinessException("插入语句中没有获取到插入字段的值信息，请检查！" + statement.getParent());
            }
            // 值可以是多条数据以前插入
            for (SQLInsertStatement.ValuesClause valuesClause : valuesClauseList) {
                List<SQLExpr> list = valuesClause.getValues();
                if (sqlExprList.size() != list.size()) {
                    throw new BusinessException("插入语句中插入字段格式和值的个数不一致，请检查！" + statement.getParent());
                }
                List<Object> objectList = new ArrayList<>();
                // 字段对应的值
                List<List<Object>> listCoulmnValue = null;
                if (!mapCoulmnValue.containsKey(tableName)) {
                    listCoulmnValue = new ArrayList<>();
                } else {
                    listCoulmnValue = mapCoulmnValue.get(tableName);
                }
                for (SQLExpr sqlExpr : list) {
                    if (sqlExpr instanceof SQLNullExpr) { //字符类型
                        objectList.add(null);
                        continue;
                    }
                    if (sqlExpr instanceof SQLCharExpr) { //字符类型
                        SQLCharExpr sqlCharExpr = (SQLCharExpr) sqlExpr;
                        if (null != sqlCharExpr) {
                            objectList.add(sqlCharExpr.getText());
                        }
                        continue;
                    }
                    if (sqlExpr instanceof SQLIntegerExpr) { //字符类型
                        SQLIntegerExpr sqlIntegerExpr = (SQLIntegerExpr) sqlExpr;
                        if (null != sqlIntegerExpr) {
                            objectList.add(sqlIntegerExpr.getNumber());
                        }
                        continue;
                    }
                    if (sqlExpr instanceof SQLMethodInvokeExpr) { // 方法类型 如 sys_guid()
                        SQLMethodInvokeExpr invokeExpr = (SQLMethodInvokeExpr) sqlExpr;
                        if (null != invokeExpr) {
                            if (StringUtil.oneOf(invokeExpr.toString(), ORACLE_FUNCTION)) {
                                throw new BusinessException("请不要使用ORACLE特殊函数！" + invokeExpr.toString() + statement.toString());
                            }
                            if (StringUtil.oneCase(invokeExpr.toString(), "sys_guid(),SYS_GUID()")) {
                                objectList.add(DateUtil.generateUUID());
                            } else if (invokeExpr.getArguments().size() > 0) {
                                SQLCharExpr sqlCharExpr = (SQLCharExpr) invokeExpr.getArguments().get(0);
                                if (DateUtil.checkStandardDate(sqlCharExpr.getText())) {
                                    objectList.add(sqlCharExpr.getText());
                                } else {
                                    //   objectList.add(DateUtil.dateToStrByFormat(new Date(), YssEnum.YSS_DEFAULT_DATE_TIME_FORMAT.getCode()));
                                    throw new BusinessException(invokeExpr.toString() + "请使用系统标准日期格式！" + YssEnum.YSS_DEFAULT_DATE_TIME_FORMAT.getCode());
                                }
                            } else {
                                throw new BusinessException("系统不支持改方法的新增，请不要使用特殊函数！" + invokeExpr.toString() + statement.toString());
                            }
                        }
                        continue;
                    }
                    if (sqlExpr instanceof OracleSysdateExpr) { // ORACLE 的 SYSDATE默认值
                        OracleSysdateExpr invokeExpr = (OracleSysdateExpr) sqlExpr;
                        if (null != invokeExpr) {
                            objectList.add(DateUtil.dateToStrByFormat(new Date(), YssEnum.YSS_DEFAULT_DATE_TIME_FORMAT.getCode()));
                        }
                        continue;
                    }
                    if (sqlExpr instanceof SQLNumberExpr) { //字符类型
                        SQLNumberExpr sqlNumberExpr = (SQLNumberExpr) sqlExpr;
                        if (null != sqlNumberExpr) {
                            objectList.add(sqlNumberExpr.getNumber());
                        }
                        continue;
                    }
                    if (sqlExpr instanceof SQLTimestampExpr) {
                        SQLTimestampExpr invokeExpr = (SQLTimestampExpr) sqlExpr;
                        if (null != invokeExpr) {
                            objectList.add(invokeExpr.getLiteral());
                        }
                        continue;
                    }
                    if (sqlExpr instanceof SQLBinaryOpExpr) { // 拼接的类型  例如 '请输入' || '管理人统一社会信用代码'
                        SQLBinaryOpExpr binaryOpExpr = (SQLBinaryOpExpr) sqlExpr;
                        objectList.add(binaryOpExpr.getLeft() + "||" + binaryOpExpr.getRight());
                        continue;
                    }
                    if (sqlExpr instanceof SQLIdentifierExpr && !CollectionUtils.isEmpty(mapDeclare)) {
                        SQLIdentifierExpr invokeExpr = (SQLIdentifierExpr) sqlExpr;
                        if (null != invokeExpr && mapDeclare.containsKey(invokeExpr.getSimpleName())) {
                            objectList.add(mapDeclare.get(invokeExpr.getSimpleName()));
                        }
                        continue;
                    }
                    throw new BusinessException("系统没有解析到你值，请联系管理员！" + sqlExpr.getParent());
                }
                listCoulmnValue.add(objectList);
                mapCoulmnValue.put(tableName, listCoulmnValue);
            }
            // 第一行为字段名称的集合
            for (Map.Entry<String, List<Object>> entry : mapCoulmnName.entrySet()) {
                if (!mapCoulmnValue.containsKey(entry.getKey())) {
                    continue;
                }
                List<List<Object>> listCoulmnValue = mapCoulmnValue.get(entry.getKey());
                listCoulmnValue.add(0, entry.getValue());
            }
            for (Map.Entry<String, List<List<Object>>> entry : mapCoulmnValue.entrySet()) {
                DatabaseConfig config = databaseConfigService.selectDatabaseConfig("RW_DB_" + entry.getKey());
                if (null == config) {
                    throw new BusinessException(entry.getKey() + "插入的数据不是基础数据，请检查！");
                }
                if (1 == config.getDataType() && StringUtils.isBlank(sqlScript.getDataBaseType())) { // 数据 要区分数据库类型 主要是插入SQL 语句的表 像结果集，ETL的部分表
                    throw new BusinessException(entry.getKey() + "该表数据需要区分数据库类型，请检查！");
                }
                msgInfo.append(this.insertBaseDataBySqlScript(sqlScript, entry.getValue(), config, connection, mapInfo, mapInfoDemandBugInfo));
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException("解析插入语句出错！" + ex.getMessage());
        }
    }

    /**
     * 解析BLOB类型字段插入的
     *
     * @param stmt
     * @param sqlScript
     * @param mapInfo
     * @param mapInfoDemandBugInfo
     * @throws Exception
     */
    private void sqlBlockStatement(SQLStatement stmt, SqlScript sqlScript, Map<String, String> mapInfo,
                                   Connection connection, Map<String, String> mapInfoDemandBugInfo, StringBuffer msgInfo) throws Exception {
        try {
            SQLBlockStatement statement = (SQLBlockStatement) stmt;
            List<SQLStatement> list = statement.getStatementList();
            if (CollectionUtils.isEmpty(list)) {
                throw new BusinessException("没有获取到插入语句信息，请检查！" + statement.getParent());
            }
            Map<String, Object> mapDeclare = new HashMap<>();
            for (SQLStatement sqlStatement : list) {
                if (sqlStatement instanceof SQLSetStatement) { // 参数
                    List<SQLAssignItem> listItem = ((SQLSetStatement) sqlStatement).getItems();
                    for (SQLAssignItem sqlAssignItem : listItem) {
                        SQLIdentifierExpr expr = (SQLIdentifierExpr) sqlAssignItem.getTarget(); // 参数名称
                        String key = expr.getSimpleName();
                        if (StringUtils.isBlank(key)) {
                            throw new BusinessException("BLOB类型的插入没有解析出对应的变量信息，请检查！" + statement.getParent());
                        }
                        SQLExpr sqlExpr = sqlAssignItem.getValue(); // 参数值
                        if (sqlExpr instanceof SQLCharExpr) {
                            SQLCharExpr invokeExpr = (SQLCharExpr) sqlExpr;
                            String value = invokeExpr.getText();
                            mapDeclare.put(key, value);
                        } else {
                            throw new BusinessException("BLOB类型的插入系统现在只支持字符类型的，请检查！" + statement.getParent());
                        }

                    }
                    continue;
                }
                if (sqlStatement instanceof OracleInsertStatement) { // 插入语句
                    OracleInsertStatement sqlInsertStatement = (OracleInsertStatement) sqlStatement;
                    this.sqlInsertStatement(sqlInsertStatement, sqlScript, mapInfo, connection, mapInfoDemandBugInfo, msgInfo, mapDeclare);
                    continue;
                }
                if (sqlStatement instanceof OracleUpdateStatement) { // 修改语句
                    OracleUpdateStatement sqlUpdateStatement = (OracleUpdateStatement) sqlStatement;
                    this.sqlUpdateStatement(sqlUpdateStatement, sqlScript, mapInfo, connection, mapInfoDemandBugInfo, mapDeclare);
                    continue;
                }
                throw new BusinessException("系统还不支持该类型的语句！" + statement.getParent());
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException("解析大字段的插入语句出错！" + ex.getMessage());
        }
    }

    /**
     * 文件数据生成对应的insert语句
     *
     * @param listData
     * @param config
     * @param connection
     * @param sqlScript  sql脚本信息
     * @throws Exception
     */
    private String insertBaseDataBySqlScript(SqlScript sqlScript, List<List<Object>> listData,
                                             DatabaseConfig config, Connection connection, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        PreparedStatement pStemtInsert = null;
        PreparedStatement pStemtUpdate = null;
        PreparedStatement pStemtSelect = null;
        PreparedStatement pStemtSelectPrimaryKey = null;
        ResultSet rs = null;
        StringBuffer msgInfo = new StringBuffer();
        try {
            // 读取数据库的字段类型
            Map<String, String> columnMap = JdbcUtil.getTableColumnNames("SELECT * FROM " + config.getCode(), connection);
            List<Object> objects = listData.get(0);
            StringJoiner bufferFieldInsert = new StringJoiner(",");
            StringJoiner bufferFieldOnly = new StringJoiner(" ");
            StringJoiner bufferFieldValueUpdate = new StringJoiner(",");
            StringJoiner bufferFieldValueInsert = new StringJoiner(",");
            List<String> dataTypeName = new ArrayList<>();
            // 业务主键字段
            List<Integer> onlyName = new ArrayList<>();
            String[] arr = config.getOnlyColumn().split(",");
            //  int keyNum = 0;  // 标识主键在第几个
            int keyNumReal = 0;  // 标识原始表真实主键在第几个
            int num = 0; // 确定唯一的字段在第几个
            for (Object object : objects) {
                if (null == object) {
                    continue;
                }
                if (StringUtils.isNotBlank(config.getPrimaryKeyColumnReal()) && config.getPrimaryKeyColumnReal().equals(object.toString())) {
                    keyNumReal = dataTypeName.size();
                }
                if (columnMap.containsKey(object.toString())) {
                    dataTypeName.add(columnMap.get(object.toString()));
                }
                // 判断唯一数据的字段
                for (String only : arr) {
                    if (only.equals(object.toString())) {
                        onlyName.add(num);
                        if (StringUtil.oneCase(object.toString(), MYSQL_KEY)) {
                            bufferFieldOnly.add(" AND IFNULL(`" + only + "`,'') = ? ");
                        } else {
                            bufferFieldOnly.add(" AND IFNULL(" + only + ",'')= ? ");
                        }
                    }
                }
                num++;
                // MYSQL关键字处理
                if (StringUtil.oneCase(object.toString(), MYSQL_KEY)) {
                    bufferFieldInsert.add("`" + object.toString() + "`");
                } else {
                    bufferFieldInsert.add(object.toString());
                }
                if (StringUtil.oneCase(object.toString(), MYSQL_KEY)) {
                    bufferFieldValueUpdate.add("`" + object.toString() + "`= ?");
                } else {
                    bufferFieldValueUpdate.add("" + object.toString() + " = ?");
                }
                bufferFieldValueInsert.add("?");
            }
            //查询语句判断是否已经存在
            StringBuffer selectSqlOnly = new StringBuffer();
            selectSqlOnly.append("SELECT * FROM " + config.getCode()).append(" WHERE 1=1");
            selectSqlOnly.append(bufferFieldOnly);
            // 判断数据是不是已经存在
            pStemtSelect = connection.prepareStatement(selectSqlOnly.toString());
            // 数据不存在insert语句
            StringBuffer insertSql = new StringBuffer();
            insertSql.append("INSERT INTO " + config.getCode()).append("(");
            // 添加文件名称和版本号
            if (1 == config.getDataType()) { // 需要区分数据库类型
                bufferFieldInsert.add("RW_DB_STATUS,RW_DB_FILE_NAME,RW_DB_VERSION,RW_DB_ADD_TIME,RW_DB_ADD_USER,RW_DB_DATABASE_TYPE,RW_DB_ID");
                bufferFieldValueInsert.add("?");
            } else {
                bufferFieldInsert.add("RW_DB_STATUS,RW_DB_FILE_NAME,RW_DB_VERSION,RW_DB_ADD_TIME,RW_DB_ADD_USER,RW_DB_ID");
            }
            insertSql.append(bufferFieldInsert).append(") VALUES (");
            bufferFieldValueInsert.add("?,?,?,?,?,?");
            insertSql.append(bufferFieldValueInsert).append(")");
            pStemtInsert = connection.prepareStatement(insertSql.toString());
            // 数据存在修改语句
            StringBuffer updateSql = new StringBuffer();
            updateSql.append("UPDATE " + config.getCode() + " SET ");
            // 添加文件名称和版本号
            if (1 == config.getDataType()) { // 需要区分数据库类型
                bufferFieldValueUpdate.add(" RW_DB_STATUS=?,RW_DB_FILE_NAME=?,RW_DB_VERSION = ?,RW_DB_EDIT_TIME=?,RW_DB_EDIT_USER=?,RW_DB_DATABASE_TYPE = ?");
            } else {
                bufferFieldValueUpdate.add(" RW_DB_STATUS=?,RW_DB_FILE_NAME=?,RW_DB_VERSION = ?,RW_DB_EDIT_TIME=?,RW_DB_EDIT_USER=?");
            }
            updateSql.append(bufferFieldValueUpdate).append(" WHERE 1=1 ").append(bufferFieldOnly);
            pStemtUpdate = connection.prepareStatement(updateSql.toString());
            // 存放字段值和数据字段类型
            // 判断是不是又业务主键重复的数据
            Map<String, String> dataMap = new HashMap<>();
            for (int i = 1; i < listData.size(); i++) {
                List<Object> objectList = listData.get(i);
                if (CollectionUtils.isEmpty(objectList)) {
                    continue;
                }
                List<Object> listInsert = new ArrayList<>();
                List<Object> listSelect = new ArrayList<>();
                // 数据拼接成Sql
                for (int k = 0; k < objectList.size(); k++) {
                    Object obj = objectList.get(k);
                    //  原始的主键字段不能为空
                    if (StringUtils.isNotBlank(config.getPrimaryKeyColumnReal()) && k == keyNumReal && (null == obj || StringUtils.isBlank(obj.toString()))) {
                        throw new BusinessException("表" + config.getCode().replace("RW_DB_", "") + config.getPrimaryKeyColumnReal() + "主键字段值不能为空！");
                    }
                    listInsert.add(obj);
                    for (Integer number : onlyName) {
                        if (k == number) {
                            listSelect.add(obj);
                        }
                    }
                }
                // 添加固定的类型 状态，文件名称，版本号，添加人，修改人(插入的时候) 添加时间，修改时间（修改的时候）
                String[] arrDataTypeName = new String[]{"DECIMAL", "VARCHAR", "VARCHAR", "TIMESTAMP", "VARCHAR"};
                if (1 == config.getDataType()) { // 需要区分数据库类型
                    arrDataTypeName = new String[]{"DECIMAL", "VARCHAR", "VARCHAR", "TIMESTAMP", "VARCHAR", "VARCHAR"};
                }
                for (String typeName : arrDataTypeName) {
                    dataTypeName.add(typeName);
                }
                // 判断插入的数据业务主键是不是存在
                StringBuffer key = new StringBuffer();
                for (Integer integer : onlyName) {
                    key.append(listInsert.get(integer)).append("=");
                }
                if (1 == sqlScript.getCoverPrimaryKey()) { // 是否按照业务主键覆盖数据
                    for (int m = 0; m < listSelect.size(); m++) {
                        JdbcUtil.addPreparedStatement(m, m, dataTypeName.get(onlyName.get(m)), listSelect, pStemtSelect, true);
                    }
                    rs = pStemtSelect.executeQuery();
                    if (rs.next()) {
                        // 修改的时候文件名不修改，重复审核导致原来数据会被删除
                        listInsert.add(ReportWorldStatusEnum.REPORT_NORMAL.getCode()); // 状态
                        listInsert.add(rs.getString("RW_DB_FILE_NAME"));
                        listInsert.add(sqlScript.getVersion());
                        listInsert.add(DateUtil.dateToStrByFormat(new Date(), YssEnum.YSS_DEFAULT_DATE_TIME_FORMAT.getCode()));
                        listInsert.add(sqlScript.getAddUser());
                        if (1 == config.getDataType()) { // 需要区分数据库类型
                            listInsert.add(sqlScript.getDataBaseType());
                        }
                        int number = 0;
                        for (int m = 0; m < listInsert.size(); m++) { //更新成最新的，包括真实的主键字段
                            JdbcUtil.addPreparedStatement(number, m, dataTypeName.get(m), listInsert, pStemtUpdate);
                            number++;
                        }
                        // 条件开始的
                        for (int m = 0; m < listSelect.size(); m++) {
                            JdbcUtil.addPreparedStatement(number + m, m, dataTypeName.get(onlyName.get(m)), listSelect, pStemtUpdate, true);
                        }
                        pStemtUpdate.addBatch();
                        // 修改数据的时候存修改前的主键值，存在 所属模块，所属客户，所属报表，需求信息
                        mapInfo.put(rs.getString(config.getPrimaryKeyColumn()), config.getCode().toUpperCase());
                        mapInfoDemandBugInfo.put(rs.getString(config.getPrimaryKeyColumn()), config.getCode().toUpperCase());
                        msgInfo.append(config.getCode().replace("RW_DB_", "")).
                                append("===【业务主键" + config.getOnlyColumn()).append("】【").append(key + "系统已经存在该条数据，该数据会被更新，请核对数据！】").append("\r\n");
                        continue;
                    }
                    rs.close();
                } else {
                    if (StringUtils.isBlank(sqlScript.getModularId()) && StringUtils.isBlank(sqlScript.getCustomerId())
                            && StringUtils.isBlank(sqlScript.getReportId())) {
                        throw new BusinessException("不覆盖业务主键的数据必须要有选择所属报表，所属模块或者所属客户，请选择所属客户，所属模块或者所属报表！");
                    }
                }
                // 添加文件名称和版本号
                listInsert.add(ReportWorldStatusEnum.REPORT_NORMAL.getCode()); // 状态
                listInsert.add(sqlScript.getId());
                listInsert.add(sqlScript.getVersion());
                listInsert.add(DateUtil.dateToStrByFormat(new Date(), YssEnum.YSS_DEFAULT_DATE_TIME_FORMAT.getCode()));
                listInsert.add(sqlScript.getAddUser());
                if (1 == config.getDataType()) { // 需要区分数据库类型
                    listInsert.add(sqlScript.getDataBaseType());
                }
                if (dataMap.containsKey(key.toString())) {
                    msgInfo.append(config.getCode().replace("RW_DB_", "")).
                            append("===【业务主键" + config.getOnlyColumn()).append("】【").append(key + "存在重复数据，已经跳过该数据，请核对数据！】").append("\r\n");
                    continue;
                }
                dataMap.put(key.toString(), key.toString());
                //  校验业务主键不一样，当时主键一致的情况
                if (1 == sqlScript.getCoverPrimaryKey() && StringUtils.isNotBlank(config.getPrimaryKeyColumnReal())) {
                    pStemtSelectPrimaryKey = connection.prepareStatement("SELECT 1 FROM " + config.getCode() + " WHERE "
                            + config.getPrimaryKeyColumnReal() + " = ?");
                    for (int m = 0; m < listInsert.size(); m++) {
                        if (m != keyNumReal) {
                            continue;
                        }
                        JdbcUtil.addPreparedStatement(0, m, dataTypeName.get(m), listInsert, pStemtSelectPrimaryKey);
                    }
                    rs = pStemtSelectPrimaryKey.executeQuery();
                    if (rs.next()) {
                        msgInfo.append(config.getCode().replace("RW_DB_", "")).
                                append("===【主键" + config.getPrimaryKeyColumnReal()).append("】【").append(listInsert.get(keyNumReal) + "数据已经存在，已经跳过该数据，请核对数据！】").append("\r\n");
                        continue;
                    }
                    rs.close();
                }
                // 插入的数据第一个放的主键
                String keyValue = DateUtil.generateUUID();
                listInsert.add(keyValue);
                dataTypeName.add("VARCHAR"); //新增的最后一个字段是系统限定的主键字段
                for (int m = 0; m < listInsert.size(); m++) {
                    JdbcUtil.addPreparedStatement(m, m, dataTypeName.get(m), listInsert, pStemtInsert);
                }
                pStemtInsert.addBatch();
                // 新增的数据 所属模块，所属客户，所属报表，需求信息
                mapInfo.put(keyValue, config.getCode().toUpperCase());
                mapInfoDemandBugInfo.put(keyValue, config.getCode().toUpperCase());
            }
            if (null != pStemtUpdate) {
                pStemtUpdate.executeBatch();
            }
            if (null != pStemtInsert) {
                pStemtInsert.executeBatch();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException(config.getCode().replace("RW_DB_", "") + "插入数据信息出错" + ex.getMessage());
        } finally {
            if (pStemtInsert != null) {   // 关闭声明
                pStemtInsert.close();
            }
            if (pStemtUpdate != null) {   // 关闭声明
                pStemtUpdate.close();
            }
            if (pStemtSelect != null) {   // 关闭声明
                pStemtSelect.close();
            }
            if (pStemtSelectPrimaryKey != null) {   // 关闭声明
                pStemtSelectPrimaryKey.close();
            }
            if (rs != null) {   // 关闭声明
                rs.close();
            }
        }
        return msgInfo.toString();
    }

    /**
     * 删除语句 修改对应数据状态已删除状态
     *
     * @return
     * @throws Exception
     */
    private void sqlDeleteStatement(SQLStatement stmt, SqlScript
            sqlScript, Map<String, String> mapInfoDemandBugInfo, Connection connection) throws Exception {
        PreparedStatement pStemtUpdate = null;
        PreparedStatement pStemtSelect = null;
        ResultSet rs = null;
        try {
            SQLDeleteStatement delete = (SQLDeleteStatement) stmt;
            SQLExprTableSource sqlTableSource = (SQLExprTableSource) delete.getTableSource();
            String tableName = sqlTableSource.getName().getSimpleName();  // 删除的表名
            if (StringUtils.isBlank(tableName)) {
                throw new BusinessException("没有获取到删除语句里的表名信息！" + sqlTableSource.getParent());
            }
            // 判断是否配置的基础数据
            DatabaseConfig config = databaseConfigService.selectDatabaseConfig("RW_DB_" + tableName.toUpperCase());
            if (null == config) {
                throw new BusinessException("插入的数据不是基础数据，请检查！" + sqlTableSource.getParent());
            }
            if (1 == config.getDataType() && StringUtils.isBlank(sqlScript.getDataBaseType())) {  // 配置要区分数据库类型的数据
                throw new BusinessException("删除的数据需要区分数据库类型，请选择数据库类型！" + sqlTableSource.getParent());
            }
            StringBuffer updateSql = new StringBuffer();
            updateSql.append("UPDATE " + config.getCode() + " SET RW_DB_STATUS = ? , RW_DB_EDIT_TIME= ?, RW_DB_EDIT_USER=? ");
            StringBuffer sqlWhere = new StringBuffer();
            SQLExpr opExpr = delete.getWhere();
            if (opExpr instanceof SQLBinaryOpExpr) {
                opExpr = delete.getWhere();
                if (null != opExpr) { // where 条件
                    if (StringUtil.oneOf(opExpr.toString(), "select,SELECT")) {
                        throw new BusinessException("删除的数据不要用子查询，请列除具体值或者按照某一列的值删除！" + sqlTableSource.getParent());
                    }
                    sqlWhere.append(opExpr);
                }
            }
            if (opExpr instanceof SQLInListExpr) { // where 条件是单独一个in的时候
                StringJoiner updateWhere = new StringJoiner(",");
                SQLInListExpr listExpr = (SQLInListExpr) opExpr;
                SQLExpr expr = listExpr.getExpr();
                if (expr instanceof SQLPropertyExpr) {
                    throw new BusinessException("删除语句中不用别名，请检查！" + sqlTableSource.getParent());
                }
                SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) listExpr.getExpr();
                sqlWhere.append(identifierExpr.getName()).append(" IN (");// 字段名
                List<SQLExpr> exprList = listExpr.getTargetList();
                for (SQLExpr sqlExpr : exprList) {
                    if (sqlExpr instanceof SQLCharExpr) {
                        SQLCharExpr charExpr = (SQLCharExpr) sqlExpr;
                        updateWhere.add("'" + charExpr.getValue() + "'");
                        continue;
                    }
                    if (sqlExpr instanceof SQLIntegerExpr) { //字符类型
                        SQLIntegerExpr sqlIntegerExpr = (SQLIntegerExpr) sqlExpr;
                        if (null != sqlIntegerExpr) {
                            updateWhere.add(sqlIntegerExpr.getNumber().toString());
                        }
                        continue;
                    }
                    throw new BusinessException("系统没有解析到你修改语句条件的值，请联系管理员！" + sqlExpr.getParent());
                }
                sqlWhere.append(updateWhere);
                sqlWhere.append(")");
            }
            if (StringUtils.isNotBlank(sqlWhere.toString())) {
                updateSql.append(" WHERE ").append(sqlWhere);
            }
            if (1 == config.getDataType()) {  // 配置要区分数据库类型的数据
                if (StringUtils.isNotBlank(sqlWhere.toString())) {
                    sqlWhere.append(" AND RW_DB_DATABASE_TYPE='").append(sqlScript.getDataBaseType()).append("'");
                } else {
                    sqlWhere.append(" WHERE RW_DB_DATABASE_TYPE='").append(sqlScript.getDataBaseType()).append("'");
                }
            }
            pStemtUpdate = connection.prepareStatement(updateSql.toString());
            pStemtUpdate.setInt(1, ReportWorldStatusEnum.REPORT_DELETED.getCode());
            pStemtUpdate.setTimestamp(2, new java.sql.Timestamp(new Date().getTime()));
            pStemtUpdate.setString(3, sqlScript.getAddUser());
            pStemtUpdate.execute();
            // 按照条件查询 对应数据的主键信息，添加修改记录
            StringBuffer selectSql = new StringBuffer();
            selectSql.append("SELECT  " + config.getPrimaryKeyColumn() + " FROM " + config.getCode());
            if (StringUtils.isNotBlank(sqlWhere.toString())) {
                selectSql.append(" WHERE ").append(sqlWhere);
            }
            pStemtSelect = connection.prepareStatement(selectSql.toString());
            rs = pStemtSelect.executeQuery();
            while (rs.next()) {
                mapInfoDemandBugInfo.put(rs.getString(1), config.getCode().toUpperCase());
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException("解析删除语句出错！" + ex.getMessage());
        } finally {
            if (pStemtUpdate != null) {   // 关闭声明
                pStemtUpdate.close();
            }
            if (pStemtSelect != null) {   // 关闭声明
                pStemtSelect.close();
            }
            if (rs != null) {   // 关闭声明
                rs.close();
            }
        }
    }

    /**
     * 执行修改语句
     *
     * @param stmt
     * @param sqlScript
     * @param mapInfo
     * @return
     * @throws Exception
     */
    private void sqlUpdateStatement(SQLStatement stmt, SqlScript
            sqlScript, Map<String, String> mapInfo, Connection connection, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        this.sqlUpdateStatement(stmt, sqlScript, mapInfo, connection, mapInfoDemandBugInfo, null);
    }

    /**
     * 执行修改语句
     *
     * @param stmt
     * @param sqlScript
     * @param mapInfo
     * @return
     * @throws Exception
     */
    private void sqlUpdateStatement(SQLStatement stmt, SqlScript
            sqlScript, Map<String, String> mapInfo, Connection connection, Map<String, String> mapInfoDemandBugInfo, Map<String, Object> mapDeclare) throws Exception {
        PreparedStatement pStemtUpdate = null;
        PreparedStatement pStemtSelect = null;
        ResultSet rs = null;
        try {
            SQLUpdateStatement updateStatement = (SQLUpdateStatement) stmt;
            SQLExprTableSource sqlTableSource = (SQLExprTableSource) updateStatement.getTableSource();
            String tableName = sqlTableSource.getName().getSimpleName();
            if (StringUtils.isBlank(tableName)) {
                throw new BusinessException("没有获取到修改句里的表名信息！" + sqlTableSource.getParent());
            }
            // 判断是否配置的基础数据
            DatabaseConfig config = databaseConfigService.selectDatabaseConfig("RW_DB_" + tableName.toUpperCase());
            if (null == config) {
                throw new BusinessException("修改的数据不是基础数据，请检查！" + sqlTableSource.getParent());
            }
            if (1 == config.getDataType() && StringUtils.isBlank(sqlScript.getDataBaseType())) {  // 配置要区分数据库类型的数据
                throw new BusinessException("修改的数据需要区分数据库类型，请选择数据库类型！" + sqlTableSource.getParent());
            }
            List<SQLUpdateSetItem> list = updateStatement.getItems();
            if (CollectionUtils.isEmpty(list)) {
                throw new BusinessException("没有获取到修改数据的SET的值，请检查！" + sqlTableSource.getParent());
            }
            StringBuffer updateSql = new StringBuffer();
            updateSql.append("UPDATE " + config.getCode() + " SET RW_DB_STATUS = ? , RW_DB_EDIT_TIME= ?, RW_DB_EDIT_USER=?, ");
            StringJoiner bufferUpdate = new StringJoiner(",");
            List<Object> valueList = new ArrayList<>();
            for (SQLUpdateSetItem item : list) {
                SQLExpr expr = item.getColumn();
                if (expr instanceof SQLPropertyExpr) {
                    throw new BusinessException("修改语句中不用别名，请检查！" + sqlTableSource.getParent());
                }
                SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) item.getColumn();
                String columnName = identifierExpr.getName(); // 修改的字段
                if (StringUtils.isBlank(columnName)) {
                    throw new BusinessException("没有获取到修改字段的信息，请检查！" + sqlTableSource.getParent());
                }
                if (StringUtil.oneCase(columnName.toUpperCase(), MYSQL_KEY)) { // mysql关键字
                    bufferUpdate.add("`" + columnName.toUpperCase() + "`=?");
                } else {
                    bufferUpdate.add(columnName.toUpperCase() + "=?");
                }
                SQLExpr sqlExpr = item.getValue();
                if (sqlExpr instanceof SQLNullExpr) { //字符类型
                    valueList.add(null);
                    continue;
                }
                if (sqlExpr instanceof SQLCharExpr) { //字符类型
                    SQLCharExpr sqlCharExpr = (SQLCharExpr) sqlExpr;
                    valueList.add(sqlCharExpr.getText());
                    continue;
                }
                if (sqlExpr instanceof SQLIntegerExpr) { //字符类型
                    SQLIntegerExpr sqlIntegerExpr = (SQLIntegerExpr) sqlExpr;
                    if (null != sqlIntegerExpr) {
                        valueList.add(sqlIntegerExpr.getNumber());
                    }
                    continue;
                }
                if (sqlExpr instanceof SQLMethodInvokeExpr) { // 方法类型 如 sys_guid()
                    SQLMethodInvokeExpr invokeExpr = (SQLMethodInvokeExpr) sqlExpr;
                    if (StringUtil.oneOf(invokeExpr.toString(), ORACLE_FUNCTION)) {
                        throw new BusinessException("请不要使用ORACLE特殊函数！" + invokeExpr.toString());
                    }
                    if (StringUtil.oneCase(invokeExpr.toString(), "sys_guid(),SYS_GUID()")) {
                        valueList.add(DateUtil.generateUUID());
                    } else if (invokeExpr.getArguments().size() > 0
                            && StringUtil.oneCase(invokeExpr.getMethodName(), "to_date,TO_DATE")) {
                   /*     if (StringUtil.oneCase(invokeExpr.getMethodName(), "replace,REPLACE")) {
                            SQLIdentifierExpr sqlCharExpr0 = (SQLIdentifierExpr) invokeExpr.getArguments().get(0);
                            SQLCharExpr sqlCharExpr1 = (SQLCharExpr) invokeExpr.getArguments().get(1);
                            SQLCharExpr sqlCharExpr2 = (SQLCharExpr) invokeExpr.getArguments().get(2);
                            valueList.add("replace(" + sqlCharExpr0.getSimpleName() + ",'" + sqlCharExpr1.getText() + "','" + sqlCharExpr2.getText() + "')");
                            continue;
                        }*/
                        SQLCharExpr sqlCharExpr = (SQLCharExpr) invokeExpr.getArguments().get(0);
                        if (DateUtil.checkStandardDate(sqlCharExpr.getText())) {
                            valueList.add(sqlCharExpr.getText());
                        } else {
                            //   valueList.add(DateUtil.dateToStrByFormat(new Date(), YssEnum.YSS_DEFAULT_DATE_TIME_FORMAT.getCode()));
                            throw new BusinessException(invokeExpr.toString() + "请使用系统标准日期格式！" + YssEnum.YSS_DEFAULT_DATE_TIME_FORMAT.getCode());
                        }
                    } else {
                        throw new BusinessException("系统不支持改方法的修改，请不要使用特殊函数！" + invokeExpr.toString());
                    }
                    continue;
                }
                if (sqlExpr instanceof OracleSysdateExpr) { // ORACLE 的 SYSDATE默认值
                    OracleSysdateExpr invokeExpr = (OracleSysdateExpr) sqlExpr;
                    valueList.add(new java.sql.Timestamp(new Date().getTime()));
                    continue;
                }
                if (sqlExpr instanceof SQLNumberExpr) { //字符类型
                    SQLNumberExpr sqlNumberExpr = (SQLNumberExpr) sqlExpr;
                    valueList.add(sqlNumberExpr.getNumber());
                    continue;
                }
                if (sqlExpr instanceof SQLTimestampExpr) {
                    SQLTimestampExpr invokeExpr = (SQLTimestampExpr) sqlExpr;
                    valueList.add(invokeExpr.getLiteral());
                    continue;
                }
                if (sqlExpr instanceof SQLBinaryOpExpr) { // 拼接的类型  例如 '请输入' || '管理人统一社会信用代码'
                    SQLBinaryOpExpr binaryOpExpr = (SQLBinaryOpExpr) sqlExpr;
                    valueList.add(binaryOpExpr.getLeft() + "||" + binaryOpExpr.getRight());
                    continue;
                }
                if (sqlExpr instanceof SQLIdentifierExpr && !CollectionUtils.isEmpty(mapDeclare)) {
                    SQLIdentifierExpr invokeExpr = (SQLIdentifierExpr) sqlExpr;
                    if (null != invokeExpr && mapDeclare.containsKey(invokeExpr.getSimpleName())) {
                        valueList.add(mapDeclare.get(invokeExpr.getSimpleName()));
                    }
                    continue;
                }
                if (sqlExpr instanceof SQLQueryExpr) { // set的值是一个查询语句
                    throw new BusinessException("修改语句请给出SET的具体值，系统不支持SET的内容是一个SELECT的语句！" + sqlExpr.getParent());
                }
                throw new BusinessException("系统没有解析到你值，请联系管理员！" + sqlExpr.getParent());
            }
            updateSql.append(bufferUpdate);
            StringBuffer sqlWhere = new StringBuffer();
            SQLExpr opExpr = updateStatement.getWhere();
            if (opExpr instanceof SQLBinaryOpExpr) {
                opExpr = updateStatement.getWhere();
                if (null != opExpr) { // where 条件
                    sqlWhere.append(opExpr);
                }
            }
            if (opExpr instanceof SQLInListExpr) { // where 条件是单独一个in的时候
                StringJoiner updateWhere = new StringJoiner(",");
                SQLInListExpr listExpr = (SQLInListExpr) opExpr;
                SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) listExpr.getExpr();
                sqlWhere.append(identifierExpr.getName()).append(" IN (");// 字段名
                List<SQLExpr> exprList = listExpr.getTargetList();
                for (SQLExpr sqlExpr : exprList) {
                    if (sqlExpr instanceof SQLCharExpr) {
                        SQLCharExpr charExpr = (SQLCharExpr) sqlExpr;
                        updateWhere.add("'" + charExpr.getValue() + "'");
                        continue;
                    }
                    if (sqlExpr instanceof SQLIntegerExpr) { //字符类型
                        SQLIntegerExpr sqlIntegerExpr = (SQLIntegerExpr) sqlExpr;
                        if (null != sqlIntegerExpr) {
                            updateWhere.add(sqlIntegerExpr.getNumber().toString());
                        }
                        continue;
                    }
                    throw new BusinessException("系统没有解析到你修改语句条件的值，请联系管理员！" + sqlExpr.getParent());
                }
                sqlWhere.append(updateWhere);
                sqlWhere.append(")");
            }
            if (StringUtils.isNotBlank(sqlWhere.toString())) {
                updateSql.append(" WHERE ").append(sqlWhere);
            }
            if (1 == config.getDataType()) {  // 配置要区分数据库类型的数据
                if (StringUtils.isNotBlank(sqlWhere.toString())) {
                    sqlWhere.append(" AND RW_DB_DATABASE_TYPE='").append(sqlScript.getDataBaseType()).append("'");
                } else {
                    sqlWhere.append(" WHERE RW_DB_DATABASE_TYPE='").append(sqlScript.getDataBaseType()).append("'");
                }
            }
            pStemtUpdate = connection.prepareStatement(updateSql.toString());
            pStemtUpdate.setInt(1, ReportWorldStatusEnum.REPORT_NORMAL.getCode());
            pStemtUpdate.setTimestamp(2, new java.sql.Timestamp(new Date().getTime()));
            pStemtUpdate.setString(3, sqlScript.getAddUser());
            for (int i = 0; i < valueList.size(); i++) {
                pStemtUpdate.setObject(4 + i, valueList.get(i));
            }
            pStemtUpdate.execute();
            // 查询修改的数据
            // 按照条件查询 对应数据的主键信息，添加修改记录
            StringBuffer selectSql = new StringBuffer();
            selectSql.append("SELECT  " + config.getPrimaryKeyColumn() + " FROM " + config.getCode());
            if (StringUtils.isNotBlank(sqlWhere.toString())) {
                selectSql.append(" WHERE ").append(sqlWhere);
            }
            pStemtSelect = connection.prepareStatement(selectSql.toString());
            rs = pStemtSelect.executeQuery();
            while (rs.next()) {
                mapInfoDemandBugInfo.put(rs.getString(1), config.getCode().toUpperCase());
            }
        } finally {
            if (pStemtUpdate != null) {   // 关闭声明
                pStemtUpdate.close();
            }
            if (pStemtSelect != null) {   // 关闭声明
                pStemtSelect.close();
            }
            if (rs != null) {   // 关闭声明
                rs.close();
            }
        }
    }

    /**
     * 创建索引语句解析
     *
     * @param stmt
     * @param sqlScript
     * @param mapInfo
     * @return
     */
    private void sqlCreateIndexStatement(SQLStatement stmt, SqlScript
            sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        SQLCreateIndexStatement statement = (SQLCreateIndexStatement) stmt;
        SQLExprTableSource tableSource = (SQLExprTableSource) statement.getTable();
        SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) tableSource.getExpr();
        String tableName = identifierExpr.getName(); // 表名
        if (StringUtils.isBlank(tableName)) {
            throw new BusinessException("没有获取到创建索引的表信息，请检查！" + statement.getParent());
        }
        Table table = this.getTableInfo(tableName);
        SQLIdentifierExpr sqlIdentifierExpr = (SQLIdentifierExpr) statement.getName();
        String indexName = sqlIdentifierExpr.getName();   // 索引名称
        // 查询是否存在该索引名字
        QueryWrapper<TableIndexed> indexedQueryWrapper = new QueryWrapper<>();
        indexedQueryWrapper.eq("TABLE_ID", table.getId());
        indexedQueryWrapper.eq("INDEXED_NAME", indexName);
        indexedQueryWrapper.select("MAX(INDEXED_SEQUENCE) AS INDEXED_SEQUENCE");
        TableIndexed indexed = tableIndexedService.getOne(indexedQueryWrapper);
        if (null != indexed) {
            throw new BusinessException("已经存在相同的索引名称，请检查！" + statement.getParent());
        }
        // 查询最大的索引顺序
        QueryWrapper<TableIndexed> tableIndexedQueryWrapper = new QueryWrapper<>();
        tableIndexedQueryWrapper.eq("TABLE_ID", table.getId());
        tableIndexedQueryWrapper.select("MAX(INDEXED_SEQUENCE) AS INDEXED_SEQUENCE");
        TableIndexed maxSequence = tableIndexedService.getOne(tableIndexedQueryWrapper);
        // 字段名称
        List<SQLSelectOrderByItem> list = statement.getItems();
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("没有获取到调整表索引的字段，请检查！" + statement.getParent());
        }
        int i = 1;
        for (SQLSelectOrderByItem item : list) {
            SQLIdentifierExpr expr = (SQLIdentifierExpr) item.getExpr();
            TableIndexed newIndexed = new TableIndexed();
            // 获取索引类型
            OracleCreateIndexStatement indexStatement = (OracleCreateIndexStatement) expr.getParent().getParent();
            newIndexed.setIndexedType(1);
            if (null != indexStatement && StringUtils.isNotBlank(indexStatement.getType())) {
                String type = indexStatement.getType().toUpperCase();
                if ("UNIQUE".equals(type)) {
                    newIndexed.setIndexedType(2);
                } else {
                    throw new BusinessException("系统还没有改索引类型，请管理员添加对应的索引类型！" + statement.getParent());
                }
            }
            newIndexed.setId(DateUtil.generateUUID());
            newIndexed.setTableId(table.getId());
            newIndexed.setIndexedName(indexName);
            newIndexed.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
            newIndexed.setAddUser(sqlScript.getAddUser());
            newIndexed.setAddTime(LocalDateTime.now());
            newIndexed.setIndexedColumnName(expr.getName());
            if (null == maxSequence || null == maxSequence.getIndexedSequence()) {
                newIndexed.setIndexedSequence(1);
            } else {
                newIndexed.setIndexedSequence(maxSequence.getIndexedSequence() + 1);
            }
            newIndexed.setIndexedColumnSequence(i);
            SQLOrderingSpecification specification = item.getType();
            if (null != specification && StringUtils.isBlank(specification.name)) { // 排序
                newIndexed.setIndexedAscDesc(specification.name.toUpperCase());
            }
            i++;
            QueryWrapper<TableIndexed> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("TABLE_ID", table.getId());
            queryWrapper.eq("INDEXED_NAME", indexName);
            queryWrapper.eq("INDEXED_COLUMN_NAME", expr.getName());
            TableIndexed indexedOld = tableIndexedService.getOne(queryWrapper);
            if (null != indexedOld) { // 已经存在索引，修改索引信息
                //   throw new BusinessException("该索引名称下面已经有该字段存在，请检查！" + statement.getParent());
                BeanUtils.copyProperties(indexedOld, newIndexed, new String[]{"id", "sequence"});
                tableIndexedService.updateById(indexedOld);
                continue;
            }
            newIndexed.setFileName(sqlScript.getId());
            tableIndexedService.save(newIndexed);
            mapInfoDemandBugInfo.put(table.getId(), ReportWorldEnum.REPORT_TABLE_CODE.getCode());
        }
    }

    /**
     * 删除索引  drop index
     *
     * @param stmt
     * @param sqlScript
     * @param mapInfo
     * @return
     */
    private void sqlDropIndexStatement(SQLStatement stmt, SqlScript
            sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        SQLDropIndexStatement statement = (SQLDropIndexStatement) stmt;
        String indexName = statement.getIndexName().getSimpleName();  // 删除的索引名称
        if (StringUtils.isBlank(indexName)) {
            throw new BusinessException("没有获取到要删除的索引名称，请检查！");
        }
        QueryWrapper<TableIndexed> wrapper = new QueryWrapper<>();
        wrapper.eq("INDEXED_NAME", indexName);
        List<TableIndexed> list = tableIndexedService.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("要删除的索引" + indexName + "不存在，请检查！");
        }
        for (TableIndexed indexed : list) {
            if (null == indexed || StringUtils.isBlank(indexed.getId())) {
                continue;
            }
            // 修改为删除状态
            indexed.setEditUser(sqlScript.getAddUser());
            indexed.setEditTime(LocalDateTime.now());
            indexed.setStatus(ReportWorldStatusEnum.REPORT_DELETED.getCode());
            mapInfoDemandBugInfo.put(indexed.getTableId(), ReportWorldEnum.REPORT_TABLE_CODE.getCode());
        }
        if (!CollectionUtils.isEmpty(list)) {
            tableIndexedService.updateBatchById(list);
        }
    }


    /**
     * Alter
     *
     * @param stmt
     * @param sqlScript
     * @param mapInfo
     * @return
     */
    private void sqlAlterTableStatement(SQLStatement stmt, SqlScript
            sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        SQLAlterTableStatement statement = (SQLAlterTableStatement) stmt;
        List<SQLAlterTableItem> items = statement.getItems();
        for (SQLAlterTableItem item : items) {
            if (item instanceof SQLAlterTableDropIndex) {
                throw new BusinessException("系统还没有处理改类型的语句，请联系管理员！");
            } else if (item instanceof SQLAlterTableAddIndex) {
                throw new BusinessException("系统还没有处理改类型的语句，请联系管理员！");
            } else if (item instanceof SQLAlterTableDropColumnItem) {  // 删除的列名
                this.sqlAlterTableDropColumnItem(item, sqlScript, mapInfo, mapInfoDemandBugInfo);
                continue;
            } else if (item instanceof SQLAlterTableAddColumn) { //添加表字段
                this.sqlAlterTableAddColumn(item, sqlScript, mapInfo, mapInfoDemandBugInfo);
                continue;
            } else if (item instanceof OracleAlterTableModify) { // 修改列信息
                this.oracleAlterTableModify(item, sqlScript, mapInfo, mapInfoDemandBugInfo);
                continue;
            } else if (item instanceof SQLAlterTableDropConstraint) {  // 删除主键
                this.sqlAlterTableDropConstraint(item, sqlScript, mapInfo, mapInfoDemandBugInfo);
                continue;
            } else if (item instanceof SQLAlterTableAddConstraint) {  // 添加主键
                this.sqlAlterTableAddConstraint(item, sqlScript, mapInfo, mapInfoDemandBugInfo);
                continue;
            } else if (item instanceof SQLAlterTableRenameColumn) { // 修改字段名称
                this.sqlAlterTableRenameColumn(item, sqlScript, mapInfo, mapInfoDemandBugInfo);
                continue;
            } else if (item instanceof SQLAlterTableRename) { // 修改表名
                this.sqlAlterTableRename(item, sqlScript, mapInfo, mapInfoDemandBugInfo);
                continue;
            }
        }
    }

    /**
     * 添加字段
     *
     * @param item
     * @param sqlScript
     * @param mapInfo
     * @return
     * @throws Exception
     */
    private void sqlAlterTableAddColumn(SQLAlterTableItem item, SqlScript sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws
            Exception {
        SQLAlterTableAddColumn addColumn = (SQLAlterTableAddColumn) item;
        SQLAlterTableStatement statement = (SQLAlterTableStatement) addColumn.getParent();
        String tableName = statement.getTableName();// 表名
        Table table = this.getTableInfo(tableName);
        List<SQLColumnDefinition> list = addColumn.getColumns();
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("没有获取到要添加的字段信息，请检查！" + addColumn.getParent());
        }
        // 查询字段现在最大顺序
        QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("TABLE_ID", table.getId());
        wrapper.select("MAX(SEQUENCE) AS SEQUENCE");
        TableDetail detailOld = tableDetailService.getOne(wrapper);
        int sequence = 1;
        if (null != detailOld && null != detailOld.getSequence()) {
            sequence = detailOld.getSequence() + 1;
        }
        for (SQLColumnDefinition definition : list) {
            if (null == definition) {
                continue;
            }
            // 字段名称
            SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) definition.getName();
            if (StringUtils.isBlank(identifierExpr.getName())) {
                throw new BusinessException("获取字段名称出错，请稍后重试！");
            }
            // 添加表字段查询是否已经存在
            QueryWrapper<TableDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("TABLE_ID", table.getId());
            detailQueryWrapper.eq("COLUMN_NAME", identifierExpr.getName().toUpperCase());
            TableDetail detailOldOne = tableDetailService.getOne(detailQueryWrapper);
            if (null != detailOldOne) { // 修改成新的
                TableDetail detail = this.getTableDetail(definition, table.getId(), sequence, sqlScript);
                if (detail.getColumnType() != detailOldOne.getColumnType()) {
                    throw new BusinessException("添加表字段信息的字段类型和之前的类型不一致，请检查！" + addColumn.getParent());
                }
                if (detail.getColumnLength() < detailOldOne.getColumnLength()) {
                    throw new BusinessException("添加表字段信息的字段长度小于之前的字段长度，请检查！" + addColumn.getParent());
                }
                BeanUtils.copyProperties(detail, detailOldOne, new String[]{"id", "sequence"});
                detailOldOne.setEditUser(sqlScript.getAddUser());
                detailOldOne.setEditTime(LocalDateTime.now());
                detailOldOne.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                detailOldOne.setVersion(sqlScript.getVersion());
                tableDetailService.updateById(detailOldOne);
                mapInfo.put(detailOldOne.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                mapInfoDemandBugInfo.put(detailOldOne.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            } else {
                TableDetail detail = this.getTableDetail(definition, table.getId(), sequence, sqlScript);
                SQLCharExpr expr = (SQLCharExpr) definition.getComment();
                if (null != expr) {
                    String columnChineseName = expr.getText();
                    if (StringUtils.isBlank(columnChineseName)) {
                        throw new BusinessException("增加字段的表没有注释信息，请检查！" + addColumn.getParent());
                    }
                    detail.setColumnChineseName(columnChineseName);
                }
                detail.setAddUser(sqlScript.getAddUser());
                detail.setAddTime(LocalDateTime.now());
                detail.setVersion(sqlScript.getVersion());
                tableDetailService.save(detail);
                mapInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                mapInfoDemandBugInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            }
        }
    }

    /**
     * 修改字段信息
     *
     * @param item
     * @param sqlScript
     * @param mapInfo
     * @return
     */
    private void oracleAlterTableModify(SQLAlterTableItem item, SqlScript sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws
            Exception {
        OracleAlterTableModify modifyColumn = (OracleAlterTableModify) item;
        SQLAlterTableStatement statement = (SQLAlterTableStatement) modifyColumn.getParent();
        String tableName = statement.getTableSource().getName().getSimpleName(); //表名
        Table table = this.getTableInfo(tableName);
        List<SQLColumnDefinition> list = modifyColumn.getColumns();
        for (SQLColumnDefinition definition : list) {
            TableDetail detail = this.getTableDetail(definition, table.getId(), 1, sqlScript, false);
            // 查询字段是否存在
            QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("TABLE_ID", table.getId());
            wrapper.eq("COLUMN_NAME", detail.getColumnName());
            TableDetail detailOld = tableDetailService.getOne(wrapper);
            if (null == detailOld) {
                throw new BusinessException("修改的字段在表中不存在，请检查！" + modifyColumn.getParent());
            }
            SQLCharExpr expr = (SQLCharExpr) definition.getComment();
            if (null != expr && StringUtils.isBlank(expr.getText())) {
                String columnChineseName = expr.getText(); // 修改的是否中文注释可以为空
                detailOld.setColumnChineseName(columnChineseName);
            }
            // 是否主键，为空的判断
            List<SQLColumnConstraint> constraintList = definition.getConstraints();
            if (!CollectionUtils.isEmpty(constraintList)) {
                for (SQLColumnConstraint constraint : constraintList) {
                    if (null == constraint) {
                        continue;
                    }
                    if (constraint instanceof SQLNotNullConstraint) {
                        detailOld.setColumnNull(2);
                    }
                    if (constraint instanceof SQLColumnPrimaryKey) {
                        detailOld.setPrimaryKey(1);
                    }
                }
            }
            if (null != detail.getColumnType()) {
                detailOld.setColumnType(detail.getColumnType());
            }
            if (null != detail.getColumnLength()) {
                detailOld.setColumnLength(detail.getColumnLength());
            }
            if (null != detail.getColumnDecimal()) {
                detailOld.setColumnDecimal(detail.getColumnDecimal());
            }
            if (StringUtils.isNotBlank(detail.getColumnDefault())) {
                detailOld.setColumnDefault(detail.getColumnDefault());
            }
            detailOld.setEditUser(sqlScript.getAddUser());
            detailOld.setEditTime(LocalDateTime.now());
            detailOld.setVersion(sqlScript.getVersion());
            mapInfo.put(detailOld.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            mapInfoDemandBugInfo.put(detailOld.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            tableDetailService.updateById(detailOld);
        }
    }

    /**
     * 删除主键
     *
     * @param item
     * @param sqlScript
     * @param mapInfo
     * @return
     * @throws Exception
     */
    private void sqlAlterTableDropConstraint(SQLAlterTableItem item, SqlScript
            sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        SQLAlterTableDropConstraint dropConstraint = (SQLAlterTableDropConstraint) item;
        SQLAlterTableStatement tableStatement = (SQLAlterTableStatement) dropConstraint.getParent();
        // 表名
        Table table = this.getTableInfo(tableStatement.getTableName());
        List<SQLAlterTableItem> itemList = tableStatement.getItems();
        for (SQLAlterTableItem tableItem : itemList) {
            SQLAlterTableDropConstraint constraint = (SQLAlterTableDropConstraint) tableItem;
            if (StringUtils.isBlank(constraint.getConstraintName().getSimpleName())) {
                throw new BusinessException("没有获取到删除主键的字段信息，请检查！" + tableStatement.getParent());
            }
            // 获取字段
            QueryWrapper<TableDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("TABLE_ID", table.getId());
            queryWrapper.eq("COLUMN_NAME", constraint.getConstraintName().getSimpleName());
            TableDetail tableDetail = tableDetailService.getOne(queryWrapper);
            if (null == tableDetail || StringUtils.isBlank(tableDetail.getId())) {
                throw new BusinessException("没有获取到删除主键的字段信息，请检查！" + tableStatement.getParent());
            }
            tableDetail.setPrimaryKey(2);
            tableDetail.setEditUser(sqlScript.getAddUser());
            tableDetail.setEditTime(LocalDateTime.now());
            tableDetail.setVersion(sqlScript.getVersion());
            tableDetailService.updateById(tableDetail);
            mapInfoDemandBugInfo.put(tableDetail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
        }
    }

    /**
     * 新增主键信息
     *
     * @param item
     * @param sqlScript
     * @param mapInfo
     * @return
     * @throws Exception
     */
    private void sqlAlterTableAddConstraint(SQLAlterTableItem item, SqlScript
            sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        SQLAlterTableAddConstraint addConstraint = (SQLAlterTableAddConstraint) item;
        OraclePrimaryKey primaryKey = (OraclePrimaryKey) addConstraint.getConstraint();
        SQLAlterTableStatement alterTableStatement = (SQLAlterTableStatement) primaryKey.getParent().getParent();
        Table table = this.getTableInfo(alterTableStatement.getTableSource().getName().getSimpleName()); // 表名
        List<SQLSelectOrderByItem> list = primaryKey.getColumns();
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("没有获取到要添加主键的字段信息，请检查！" + addConstraint.getParent());
        }
        for (SQLSelectOrderByItem orderByItem : list) {
            SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) orderByItem.getExpr();
            // 查询要设置字段主键的字段信息是否存在
            QueryWrapper<TableDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("TABLE_ID", table.getId());
            queryWrapper.eq("COLUMN_NAME", identifierExpr.getName()); // 字段名称
            TableDetail detail = tableDetailService.getOne(queryWrapper);
            if (null == detail) {
                throw new BusinessException("添加主键的字段在表结构信息中不存在，请检查！" + addConstraint.getParent());
            }
            detail.setPrimaryKey(1);
            detail.setEditUser(sqlScript.getAddUser());
            detail.setEditTime(LocalDateTime.now());
            detail.setVersion(sqlScript.getVersion());
            tableDetailService.updateById(detail);
            mapInfoDemandBugInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
        }
    }

    /**
     * 修改表字段名称
     *
     * @param item
     * @param sqlScript
     * @param mapInfo
     * @return
     * @throws Exception
     */
    private void sqlAlterTableRenameColumn(SQLAlterTableItem item, SqlScript
            sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        SQLAlterTableRenameColumn renameColumn = (SQLAlterTableRenameColumn) item;
        SQLAlterTableStatement statement = (SQLAlterTableStatement) item.getParent();
        String tableName = statement.getTableSource().getName().getSimpleName();
        Table table = this.getTableInfo(tableName);
        SQLIdentifierExpr expr = (SQLIdentifierExpr) renameColumn.getColumn(); // 修改前的字段
        if (null == expr || StringUtils.isBlank(expr.getName())) {
            throw new BusinessException("没有获取到语句里修改前的表字段信息，请检查！" + renameColumn.getParent());
        }
        String columnName = expr.getName();
        SQLIdentifierExpr renameExpr = (SQLIdentifierExpr) renameColumn.getTo();  //修改后的字段
        if (null == expr || StringUtils.isBlank(renameExpr.getName())) {
            throw new BusinessException("没有获取到要修改的字段的名称，请检查！" + renameColumn.getParent());
        }
        String renameName = renameExpr.getName();
        // 查询修改前的字段是否存在
        QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("TABLE_ID", table.getId());
        wrapper.eq("COLUMN_NAME", columnName.toUpperCase());
        TableDetail detail = tableDetailService.getOne(wrapper);
        if (null == detail) {
            throw new BusinessException("没有获取到修改前的表字段信息，请检查！" + renameColumn.getParent());
        }
        TableDetail newDetail = new TableDetail();
        BeanUtils.copyProperties(detail, newDetail);
        detail.setStatus(ReportWorldStatusEnum.REPORT_DELETED.getCode()); // 原来的字段设置为已删除
        detail.setEditUser(sqlScript.getAddUser());
        detail.setEditTime(LocalDateTime.now());
        detail.setVersion(sqlScript.getVersion());
        tableDetailService.updateById(detail);
        mapInfoDemandBugInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
        // 查询修改前的字段是否存在
        QueryWrapper<TableDetail> wrapperOld = new QueryWrapper<>();
        wrapperOld.eq("TABLE_ID", table.getId());
        wrapperOld.eq("COLUMN_NAME", renameName.toUpperCase());
        TableDetail detailOld = tableDetailService.getOne(wrapperOld);
        if (null != detailOld) { // 已经存在，就直接修改状态
            detailOld.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
            detailOld.setColumnName(renameName);
            detailOld.setEditUser(sqlScript.getAddUser());
            detailOld.setEditTime(LocalDateTime.now());
            detailOld.setVersion(sqlScript.getVersion());
            detailOld.setOriginalColumName(columnName);
            tableDetailService.updateById(detailOld);
            mapInfo.put(detailOld.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            mapInfoDemandBugInfo.put(detailOld.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
        } else {
            newDetail.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
            newDetail.setId(DateUtil.generateUUID());
            newDetail.setColumnName(renameName);
            newDetail.setAddUser(sqlScript.getAddUser());
            newDetail.setAddTime(LocalDateTime.now());
            newDetail.setVersion(sqlScript.getVersion());
            newDetail.setOriginalColumName(columnName);
            newDetail.setColumnChineseName(detail.getColumnChineseName()); //中文描述还是取之前的
            tableDetailService.save(newDetail);
            mapInfo.put(newDetail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            mapInfoDemandBugInfo.put(newDetail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
        }
    }

    /**
     * 删除表字段
     *
     * @param item
     * @param sqlScript
     * @param mapInfo
     * @return
     * @throws Exception
     */
    private void sqlAlterTableDropColumnItem(SQLAlterTableItem item, SqlScript
            sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws Exception {
        SQLAlterTableDropColumnItem dropColumn = (SQLAlterTableDropColumnItem) item;
        SQLAlterTableStatement statement = (SQLAlterTableStatement) dropColumn.getParent();
        String tableName = statement.getTableSource().getName().getSimpleName();
        Table table = this.getTableInfo(tableName);
        List<SQLName> list = dropColumn.getColumns();
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("没有获取到要删除表字段的信息，请检查！" + statement.getParent());
        }
        for (SQLName sqlName : list) {
            SQLIdentifierExpr expr = (SQLIdentifierExpr) sqlName;
            String columnName = expr.getName();
            QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("TABLE_ID", table.getId());
            wrapper.eq("COLUMN_NAME", columnName.toUpperCase());
            TableDetail detail = tableDetailService.getOne(wrapper);
            if (null == detail) {
                throw new BusinessException("没有获取到删除表对应的字段信息，请检查！" + statement.getParent());
            }
            detail.setEditUser(sqlScript.getAddUser());
            detail.setEditTime(LocalDateTime.now());
            detail.setVersion(sqlScript.getVersion());
            detail.setStatus(ReportWorldStatusEnum.REPORT_DELETED.getCode());
            mapInfoDemandBugInfo.put(detail.getId(), ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            tableDetailService.updateById(detail);
        }
    }

    /**
     * 修改表名
     *
     * @param item
     * @param sqlScript
     * @param mapInfo
     * @return
     * @throws Exception
     */
    private void sqlAlterTableRename(SQLAlterTableItem item, SqlScript sqlScript, Map<String, String> mapInfo, Map<String, String> mapInfoDemandBugInfo) throws
            Exception {
        SQLAlterTableRename tableRename = (SQLAlterTableRename) item;
        SQLAlterTableStatement statement = (SQLAlterTableStatement) tableRename.getParent();
        String tableName = statement.getTableSource().getName().getSimpleName(); // 表名
        Table table = this.getTableInfo(tableName);
        SQLExprTableSource tableSource = tableRename.getTo(); //要修改成的表名
        SQLIdentifierExpr expr = (SQLIdentifierExpr) tableSource.getExpr();
        String tableNameNew = expr.getName();// 要修改成的表名
        if (null == expr || StringUtils.isBlank(expr.getName())) {
            throw new BusinessException("没有获取到修改的表名信息，请检查！" + statement.getParent());
        }
        // 获取要修改的表名是不是已经存在
        QueryWrapper<Table> wrapper = new QueryWrapper<>();
        wrapper.eq("NAME", tableNameNew.toUpperCase());
        Table tableNew = tableService.getOne(wrapper);
        if (null != tableNew) { // 已经存在表名
            throw new BusinessException("要修改的表名，已经存在了，请检查！" + statement.getParent());
        }
        table.setName(expr.getName());
        table.setEditUser(sqlScript.getAddUser());
        table.setEditTime(LocalDateTime.now());
        table.setVersion(sqlScript.getVersion());
        //  table.setFileName(sqlScript.getId());
        table.setOriginalTableName(table.getName());
        tableService.updateById(table);
        mapInfo.put(table.getId(), ReportWorldEnum.REPORT_TABLE_CODE.getCode());
        mapInfoDemandBugInfo.put(table.getId(), ReportWorldEnum.REPORT_TABLE_CODE.getCode());
    }

    /**
     * 获取表信息
     *
     * @param tableName
     * @return
     * @throws Exception
     */
    private Table getTableInfo(String tableName) throws Exception {
        if (StringUtils.isBlank(tableName)) {
            throw new BusinessException(tableName + "没有获取到表名称信息");
        }
        QueryWrapper<Table> wrapper = new QueryWrapper<>();
        wrapper.eq("NAME", tableName.toUpperCase());
        Table table = tableService.getOne(wrapper);
        if (null == table) {
            log.error("系统不存在需要创建索引的表信息！");
            throw new BusinessException(tableName + "系统不存在表信息，请检查！");
        }
        return table;
    }

    /**
     * 插入文件里的的所属模块，客户，报表
     *
     * @param sqlScript
     * @param mapInfo
     * @throws Exception
     */
    public void insertDataBaseSign(SqlScript sqlScript, Map<String, String> mapInfo) throws Exception {
     /*   List<DataModular> dataModulars = new ArrayList<>();
        List<DataReport> dataReports = new ArrayList<>();
        List<DataCustomer> dataCustomers = new ArrayList<>();*/
        //  循环基础数据的对应模块，客户，需求bug
        for (Map.Entry<String, String> entry : mapInfo.entrySet()) {
            if (null == entry || StringUtils.isBlank(entry.getKey()) || StringUtils.isBlank(entry.getValue())) {
                continue;
            }
            if (StringUtils.isNotBlank(sqlScript.getModularId())) {
                // 先删除在插入数据
                QueryWrapper<DataModular> modularQueryWrapper = new QueryWrapper<>();
                modularQueryWrapper.eq("DATA_ID", entry.getKey());
                modularQueryWrapper.eq("MODULAR_ID", sqlScript.getModularId());
                modularQueryWrapper.eq("DATA_CODE", entry.getValue());
                dataModularService.remove(modularQueryWrapper);
                DataModular modular = new DataModular();
                modular.setId(DateUtil.generateUUID());
                modular.setDataCode(entry.getValue());
                modular.setFileName(sqlScript.getId());
                modular.setDataId(entry.getKey());
                modular.setModularId(sqlScript.getModularId());
                modular.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                modular.setAddUser(sqlScript.getAddUser());
                modular.setAddTime(LocalDateTime.now());
                // dataModulars.add(modular);
                dataModularService.save(modular);
            }
            if (StringUtils.isNotBlank(sqlScript.getReportId())) {
                QueryWrapper<DataReport> reportQueryWrapper = new QueryWrapper<>();
                reportQueryWrapper.eq("DATA_ID", entry.getKey());
                reportQueryWrapper.eq("REPORT_ID", sqlScript.getReportId());
                reportQueryWrapper.eq("DATA_CODE", entry.getValue());
                dataReportService.remove(reportQueryWrapper);
                DataReport report = new DataReport();
                report.setId(DateUtil.generateUUID());
                report.setDataCode(entry.getValue());
                report.setFileName(sqlScript.getId());
                report.setDataId(entry.getKey());
                report.setReportId(sqlScript.getReportId());
                report.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                report.setAddUser(sqlScript.getAddUser());
                report.setAddTime(LocalDateTime.now());
                // dataReports.add(report);
                dataReportService.save(report);
            }
            if (StringUtils.isNotBlank(sqlScript.getCustomerId())) {
                QueryWrapper<DataCustomer> customerQueryWrapper = new QueryWrapper<>();
                customerQueryWrapper.eq("DATA_ID", entry.getKey());
                customerQueryWrapper.eq("CUSTOMER_ID", sqlScript.getCustomerId());
                customerQueryWrapper.eq("DATA_CODE", entry.getValue());
                dataCustomerService.remove(customerQueryWrapper);
                DataCustomer customer = new DataCustomer();
                customer.setId(DateUtil.generateUUID());
                customer.setDataCode(entry.getValue());
                customer.setFileName(sqlScript.getId());
                customer.setDataId(entry.getKey());
                customer.setCustomerId(sqlScript.getCustomerId());
                customer.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                customer.setAddUser(sqlScript.getAddUser());
                customer.setAddTime(LocalDateTime.now());
                // dataCustomers.add(customer);
                dataCustomerService.save(customer);
            }
        }
    /*    if (!CollectionUtils.isEmpty(dataModulars)) {
            dataModularService.saveBatch(dataModulars);
        }
        if (!CollectionUtils.isEmpty(dataReports)) {
            dataReportService.saveBatch(dataReports);
        }
        if (!CollectionUtils.isEmpty(dataCustomers)) {
            dataCustomerService.saveBatch(dataCustomers);
        }*/
    }


    /**
     * 插入文件数据对应的需求BUG
     *
     * @param sqlScript
     * @param mapInfo
     * @param mapDemandBugInfo
     * @throws Exception
     */
    private void insertDataBasedataDemandBug(SqlScript sqlScript, Map<String, String> mapInfo, Map<String, String> mapDemandBugInfo) throws Exception {
        List<DataDemandBug> dataDemandBugs = new ArrayList<>();
        //  循环基础数据的对应模块，客户，需求bug
        for (Map.Entry<String, String> entry : mapInfo.entrySet()) {
            if (null == entry || StringUtils.isBlank(entry.getKey()) || StringUtils.isBlank(entry.getValue())) {
                continue;
            }
            // 修改记录信息
            if (StringUtils.isNotBlank(sqlScript.getDemandBugId())
                    && !CollectionUtils.isEmpty(mapDemandBugInfo)) {
                QueryWrapper<DataDemandBug> updateInfoQueryWrapper = new QueryWrapper<>();
                updateInfoQueryWrapper.eq("DATA_ID", entry.getKey());
                updateInfoQueryWrapper.eq("DEMAND_BUG_ID", sqlScript.getDemandBugId());
                updateInfoQueryWrapper.eq("DATA_CODE", entry.getValue());
                dataDemandBugService.remove(updateInfoQueryWrapper);
                DataDemandBug dataDemandBug = new DataDemandBug();
                dataDemandBug.setId(DateUtil.generateUUID());
                dataDemandBug.setDataCode(entry.getValue());
                dataDemandBug.setDemandBugId(sqlScript.getDemandBugId());
                dataDemandBug.setDataId(entry.getKey());
                dataDemandBug.setDataCode(entry.getValue());
                dataDemandBug.setFileName(sqlScript.getId());
                dataDemandBug.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                dataDemandBug.setAddUser(sqlScript.getAddUser());
                dataDemandBug.setAddTime(LocalDateTime.now());
                dataDemandBugs.add(dataDemandBug);
            }
        }
        if (!CollectionUtils.isEmpty(dataDemandBugs)) {
            dataDemandBugService.saveBatch(dataDemandBugs);
        }
    }


    /**
     * 检查表和字段的规范
     *
     * @param sqlScript
     * @param mapInfoDemandBugInfo
     * @throws Exception
     */
    private void tableStandardCheckInfo(SqlScript sqlScript, Map<String, String> mapInfoDemandBugInfo, StringBuffer msgInfo) throws Exception {
        if (CollectionUtils.isEmpty(mapInfoDemandBugInfo)) {
            return;
        }
        try {
            for (Map.Entry<String, String> entry : mapInfoDemandBugInfo.entrySet()) {
                if (null == entry || StringUtils.isBlank(entry.getKey()) || StringUtils.isBlank(entry.getValue())) {
                    continue;
                }
                if (ReportWorldEnum.REPORT_TABLE_CODE.getCode().equals(entry.getValue())) {
                    QueryWrapper<Table> wrapper = new QueryWrapper<>();
                    wrapper.eq("ID", entry.getKey());
                    Table table = tableService.getOne(wrapper);
                    if (null == table || StringUtils.isBlank(table.getId())) {
                        throw new BusinessException("检查表规范的时候，获取表信息失败！");
                    }
                    QueryWrapper<TableDetail> wrapperDetail = new QueryWrapper<>();
                    wrapperDetail.eq("TABLE_ID", table.getId());

                    // 表和字段的规范
                    table.setModular(sqlScript.getModularId());
                    table.setCustomer(sqlScript.getCustomerId());
                    table.setReport(sqlScript.getReportId());
                    tableStandardCheckService.tableStandardCheckInfo(table, true);

                } else if (ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode().equals(entry.getValue())) {
                    QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
                    wrapper.eq("ID", entry.getKey());
                    TableDetail tableDetail = tableDetailService.getOne(wrapper);
                    if (null == tableDetail || StringUtils.isBlank(tableDetail.getId())) {
                        throw new BusinessException("检查表字段规范的时候，获取表字段信息失败！");
                    }
                    tableDetailStandardCheckService.tableDetailStandardCheckInfo(tableDetail);
                }
            }
        } catch (Exception ex) {
            throw new BusinessException(ex.getMessage());
        }
    }

    /**
     * 审核退回功能
     *
     * @param ids
     * @param msg
     * @return
     */
    public void rebutSqlScript(String ids, String msg) throws Exception {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("获取脚本管理数据失败，请稍后重试！");
        }
        List<String> idList = JSONArray.parseArray(ids, String.class);
        if (CollectionUtils.isEmpty(idList)) {
            throw new BusinessException("获取脚本管理数据失败，请稍后重试！");
        }
        UpdateWrapper<SqlScript> wrapper = new UpdateWrapper<>();
        wrapper.in("ID", idList);
        SqlScript sqlScript = new SqlScript();
        sqlScript.setApprovalReason(msg);
        sqlScript.setStatus(ReportWorldStatusEnum.REPORT_FAIL_REVIEW.getCode());
        sqlScript.setEditTime(LocalDateTime.now());
        sqlScript.setEditUser(redisCacheManager.getLoginUserInfo().getLoginId());
        this.update(sqlScript, wrapper);
        QueryWrapper<SqlScript> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("ID", idList);
        List<SqlScript> list = this.list();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        for (SqlScript script : list) {
            if (null == script || StringUtils.isBlank(script.getAddWecomUrl()) || map.containsKey(script.getAddUserName())) {
                continue;
            }
            map.put(script.getAddUserName(), script.getAddUserName());
            weComService.sendMessage(script.getAddWecomUrl(), "@" + script.getAddUserName() + " 你的脚本被退回，原因：" + script.getApprovalReason());
        }
    }

    /**
     * 导出脚本文件
     *
     * @param response
     * @param ids
     */
    public void downSqlScriptFile(HttpServletResponse response, String ids) throws Exception {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("获取脚本管理失败，请稍后重试！");
        }
        List<String> idList = JSONArray.parseArray(ids, String.class);
        if (CollectionUtils.isEmpty(idList)) {
            throw new BusinessException("获取脚本管理失败，请稍后重试！");
        }
        try {
            QueryWrapper<SqlScript> wrapper = new QueryWrapper<>();
            wrapper.in("ID", idList);
            wrapper.in("STATUS", ReportWorldStatusEnum.REPORT_NORMAL.getCode());
            wrapper.orderByAsc("ADD_TIME");
            List<SqlScript> scriptList = this.list(wrapper);
            if (CollectionUtils.isEmpty(scriptList)) {
                throw new BusinessException("没有获取到要导出的脚本，请稍后重试！");
            }
            StringBuffer buffer = new StringBuffer();
            for (SqlScript sqlScript : scriptList) {
                if (null == sqlScript || StringUtils.isBlank(sqlScript.getSqlScript())) {
                    continue;
                }
                buffer.append(sqlScript.getSqlScript()).append("\r\n");
            }
            FileWriterUtil.downloadFileBuffer(response, buffer.toString(), ReportWorldFileNameEnum.SQL_SCRIPT.getCode(),
                    ReportWorldFileNameEnum.SQL_SCRIPT.getDesc());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException(ex.getMessage());
        }
    }


    /**
     * 基础数据的检查
     *
     * @param sqlScript
     * @param mapInfoDemandBugInfo
     * @throws Exception
     */
    public void dataBaseCheckInfo(Connection connection, SqlScript sqlScript, Map<String, String> mapInfoDemandBugInfo, StringBuffer msgInfo) throws Exception {
        if (CollectionUtils.isEmpty(mapInfoDemandBugInfo)) {
            return;
        }
        PreparedStatement pStemtSelect = null;
        ResultSet rs = null;
        try {
            Map<String, String> map = new HashMap();
            for (Map.Entry<String, String> entry : mapInfoDemandBugInfo.entrySet()) {
                if (null == entry || StringUtils.isBlank(entry.getKey()) || StringUtils.isBlank(entry.getValue())) {
                    continue;
                }
                if (!entry.getValue().startsWith("RW_DB_") || map.containsKey(entry.getValue())) {
                    continue;
                }
                if (entry.getKey().equals(ReportWorldEnum.REPORT_TABLE_CODE.getCode())) {
                    msgInfo.append(tableCheckService.checkTableAndDataSqlInfo(connection));
                    continue;
                }
                // 查询对应表配置的检查SQL语句
                String tableName = entry.getValue().replace("RW_DB_", "");
                // 查询表ID
                QueryWrapper<Table> wrapper = new QueryWrapper<>();
                wrapper.eq("NAME", tableName);
                Table table = tableService.getOne(wrapper);
                if (null == table || StringUtils.isBlank(table.getId())) {
                    continue;
                }
                QueryWrapper<TableCheck> wrapperCheck = new QueryWrapper<>();
                wrapperCheck.eq("TABLE_ID", table.getId());
                wrapperCheck.orderByAsc("SEQUENCE");
                wrapperCheck.eq("STATUS", ReportWorldStatusEnum.REPORT_NORMAL.getCode());
                List<TableCheck> list = tableCheckService.list(wrapperCheck);
                if (CollectionUtils.isEmpty(list)) {
                    continue;
                }
                DatabaseConfig config = databaseConfigService.selectDatabaseConfig(entry.getValue());
                if (null == config || StringUtils.isBlank(config.getOnlyColumn())) {
                    continue;
                }
                String[] arr = config.getOnlyColumn().split(",");
                if (null == arr || arr.length == 0) {
                    continue;
                }
                StringBuffer msg = new StringBuffer();
                for (TableCheck check : list) {
                    if (null == check || StringUtils.isBlank(check.getDatasql())) {
                        continue;
                    }
                    String sql = check.getDatasql(); // 检查的SQL语句
                    // 查询
                    pStemtSelect = connection.prepareStatement(sql);
                    rs = pStemtSelect.executeQuery();
                    StringBuffer buffer = new StringBuffer();
                    while (rs.next()) {
                        buffer.append("\r\n");
                        for (String cloum : arr) {
                            if (StringUtils.isBlank(cloum)) {
                                continue;
                            }
                            buffer.append("【").append(cloum).append("==").append(rs.getString(cloum)).append("】");
                        }
                    }
                    rs.close();
                    if (buffer.length() > 0) {
                        if (1 == check.getErrorType()) { // 警告
                            msgInfo.append("警告：表" + table.getName()).append("业务主键" + buffer).append("校验不通过，原因【").append(check.getErrorMsg()).append("】").append("\r\n");
                            continue;
                        }
                        msg.append("错误：表" + table.getName()).append("业务主键" + buffer).append("校验不通过，原因【")
                                .append(check.getErrorMsg()).append("】").append("\r\n");
                        throw new BusinessException(msg.toString());
                    }
                }
                map.put(entry.getValue(), entry.getValue());
            }
        } catch (Exception ex) {
            throw new BusinessException("校验语句执行失败！" + ex.getMessage());
        } finally {
            if (rs != null) {   // 关闭记录集
                rs.close();
            }
            if (pStemtSelect != null) {   // 关闭声明
                pStemtSelect.close();
            }
        }
    }

}
